c# - Linq 选择最新的组层次结构

标签 c# .net linq asp.net-mvc-4

如果存在自引用层次结构时的记录,我想获取每个组的最新记录。

我的表格是这样的:

RecordId CreatedDate ParentRecordId
   1     2012/05/13       NULL   
   2     2012/05/13       NULL   
   3     2012/05/14        1     
   4     2012/05/15        3     

我只想选择最新版本的记录。
所以在这种情况下我只想选择 RecordId = 2 和 RecordId =4。

这是我目前所拥有的,但我被卡住了。

     db.Records
       .Where(x => x.ParentRecordId!= null).GroupBy(x => x.ParentRecordId)
       .SelectMany(x=>x.OrderByDescending(y=>y.CreatedDate).Take(1)).ToList();

最佳答案

我的左连接有点欠缺,但像这样应该可以做到;

var query = from r1 in db.Records
            join r2 in db.Records
                on r1.RecordId equals r2.ParentRecordId into rec
            from r in rec.DefaultIfEmpty()
            where r == null
            select r1;

关于c# - Linq 选择最新的组层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16488479/

相关文章:

带有 ascx 控件的 Javascript

c# - 存储来自 C# 应用程序的数据

c# - WPF重构: Moving DataTemplate to another file

c# - LINQ 查找大于/小于输入的最接近数字

Linq OrderBy 但如果 "the"忽略第一个单词

c# - 当我只知道集合的类型时,如何在 T 的 c# 通用集合中找到 T 的类型?

c# - 在 C# 中从数据库加载组合框

c# - Linq 将查询表达为 Lambda 查询

c# - C 和 C# 实现之间的 AES/CBC 加密差异

c# - YouTube API - 没有 channel Logo 参数?