Lambda Expression for Latest Date

17,884

Solution 1

var latest = model.OrderByDescending(m => m.Date).FirstOrDefault();

Solution 2

To make an expression that determines if the date is the latest, you need to know the latest date, i.e.:

DateTime latestDate = items.Max(f => f.Date);

var latestItems = items.Where(f => f.Date == latestDate);

Another approach would be to sort the items:

var latestItem = items.OrderBy(f => f.Date).First();

Or use Aggregate:

var latestItem = items.Aggregate((d, v) => v.Date > d.Date ? v : d);

Solution 3

Given that you've not provided any information about the name of your entities (I'm assuming foos here); something like this:

var latest = foos.OrderByDescending(f => f.Date).FirstOrDefault();

And if there are more than one with the max date (I know you said 'the Foo with the latest...' but I don't know the resolution of your times here) than you'll actually be after something more like Guffa's answer.

Be aware that either solution will benefit massively from an index on the date column. If there is no index and the table gets large? Then it could be very slow.

Solution 4

Try this:

DateTime maxDate = FooCollection.Max(f=>f.Date)
Share:
17,884
evablack
Author by

evablack

Updated on June 08, 2022

Comments

  • evablack
    evablack almost 2 years

    Let's say i have a Model defined as: Foo {Id, Date}.

    Is there a way to make a boolean lambda expression so that I could get the Foo with the latest date? something along the lines of (f => f.Date IsLatest)?