Get minimum and maximum time value from list of object property using Linq

15,717

Solution 1

var minStartTime = settings.Min(setting => setting.StartTime);    // returns 8am
var maxEndTime = settings.Max(setting => setting.EndTime);        // returns 5pm

This returns the lowest and highest times. Other answers are telling you how to get the difference between max and min, which does not appear to be what you asked for.

Solution 2

Assuming you want a minimum and maximum of the time deltas:

Settings[] settings = ...;

var max = settings.Max(s => s.EndTime - s.StartTime);
var min = settings.Min(s => s.EndTime - s.StartTime);

Solution 3

Do it like this

var max = (from item in myList
      select item.StartTime - item.EndTime).Max()

var min = (from item in myList
      select item.StartTime - item.EndTime).Min()
Share:
15,717
PramodChoudhari
Author by

PramodChoudhari

Software Developer

Updated on June 26, 2022

Comments

  • PramodChoudhari
    PramodChoudhari almost 2 years

    I have settings object with property

    class Settings
    {
        DateTime StartTime;
        DateTime EndTime;
    }
    

    and I have created a list of this setting object.

    How can I get the MaxTime and MinTime from the collection of objects using LINQ?

  • PramodChoudhari
    PramodChoudhari over 13 years
    obj1.StartTime=8AM, obj1.EndTime=5PM,
  • Cameron
    Cameron over 13 years
    @PramodChoudhari: Not quite sure what you're trying to say, but with those values the difference between them (EndTime - StartTime) would be a TimeSpan structure with the Hours property set to 9. See the - operator for DateTimes.
  • JK.
    JK. over 13 years
    -1 OP just asked for the max and min values not the difference between the two.
  • Cameron
    Cameron over 13 years
    @JK: OP asked for min and max across an object with two fields -- what he meant was subject to interpretation :-)
  • cjk
    cjk over 13 years
    @Pramod - if this is the answer you want then click the little tick mark next to the current number of votes the question has...
  • Bazzz
    Bazzz over 13 years
    +1 for correct interpretation of the question and not typing what you expect the OP means.
  • JK.
    JK. over 13 years
    I see 4 different comments about how to accept an answer .... and no accepted answer. Oh well never mind, next question please!
  • Cameron
    Cameron over 13 years
    @Bazzz: JK also guessed as to what the OP meant -- it just happens that his interpretation was what the OP wanted, and mine was not. Interpretation is "typing what you expect the OP means"