PramodChoudhari
PramodChoudhari

Reputation: 2553

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

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?

Upvotes: 2

Views: 15978

Answers (3)

Shekhar_Pro
Shekhar_Pro

Reputation: 18420

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()

Upvotes: 1

JK.
JK.

Reputation: 21808

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.

Upvotes: 10

Cameron
Cameron

Reputation: 98746

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);

Upvotes: 2

Related Questions