简体   繁体   中英

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!

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.

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

It should be

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

GroupBy is definitely supported by Linq-to-Entities

So the answer is:

var query =
    from alert in m_alerts
    group alert by alert.Identifier
          into g 
          select new 
          {
        GroupIdentifier = g.Key,
        UpdateDateTime = g.Max(p => p.UpdateDateTime) 
          };

This will return the most recent records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM