Lambda Expression for Latest Date

c# entity-framework lambda linq

Question

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

1
7
4/11/2012 10:57:00 AM

Accepted Answer

var latest = model.OrderByDescending(m => m.Date).FirstOrDefault();
20
4/11/2012 11:09:40 AM

Popular Answer

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow