使用LINQ to Entities选择最新记录

Beg*_*tya 10 c# linq linq-to-entities

我有一个简单的Linq to Enities表来查询并使用Date字段获取最新的记录

所以我尝试了这段代码:

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();
Run Code Online (Sandbox Code Playgroud)

错误:NotSupportedException:不支持方法"GroupBy".

有没有其他方法可以做到这一点?非常感谢!

小智 11

我有类似的需求.我希望得到键入的记录,而不是一个新的匿名对象.要做到这一点.第一个()可以帮助.

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

使用OrderByDescending对它们进行排序,并使用First()进行排序.您已按标识符对它们进行分组,因此您应该只获取每个标识符的最新记录.


Beg*_*tya 0

所以答案是:

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) 
          };
Run Code Online (Sandbox Code Playgroud)

这将返回最新的记录。