Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select most recent records using LINQ to Entities

I have a simple Linq to Enities table to query and get the most recent records using Date field

So I tried this code:

IQueryable<Alert> alerts = GetAlerts();
IQueryable<Alert> latestAlerts =
    from a in alerts
    group a by a.UpdateDateTime into g
    select g.OrderBy(a => a.Identifier).First();

Error: NotSupportedException: The method 'GroupBy' is not supported.

Is there any other way to get do it? Thanks a lot!

like image 264
Begemotya Avatar asked May 03 '10 20:05

Begemotya


2 Answers

I've had a similair need. I want to get the typed record back, not a new anonymous object. To do that .First() can help.

var query = from alert in m_alerts
        group alert by alert.Identifier into a
        select a.OrderByDescending(g => g.UpdateDateTime).First();

Use the OrderByDescending to order them and take the top one with First(). You've grouped them by your identifier so you should only get the newest record for each identifier.

like image 120
Rowan Blaqflame Avatar answered Oct 22 '22 02:10

Rowan Blaqflame


If there isn't a reason to group it, you could just switch your query up a little:

IQueryable<Alert> alerts = GetAlerts();
IQueryable latestAlerts = alerts.OrderByDescending(a => a.UpdateDateTime);
like image 39
Benny Avatar answered Oct 22 '22 03:10

Benny