开发者

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.

开发者_如何学JAVA

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜