简体   繁体   English

使用LINQ to Entities选择最新记录

[英]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 我有一个简单的Linq to Enities表来查询并使用Date字段获取最新的记录

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. 错误:NotSupportedException:不支持方法“GroupBy”。

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(). 使用OrderByDescending对它们进行排序,并使用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 Linq-to-Entities肯定支持GroupBy

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. 这将返回最新的记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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