Linq选择最近的组层次结构

本文关键字:层次结构 最近 选择 Linq | 更新日期: 2023-09-27 18:12:59

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

我的表是这样的:

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

Linq选择最近的组层次结构

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

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;

回答"获取没有其他条目认为我是父条目的所有条目"的查询如何?这听起来是一样的,除非我理解错了:

db.Records.Where(x => !db.Records
    .Select(r => r.ParentRecordId).Contains(x.RecordId))

然而,我对你所说的"循环"是什么意思有点困惑。层次结构怎么可能是循环的?

您应该首先获得ParentRecordId s的列表,然后检查RecordId是否在该列表中,如果是,那么我们应该将其从结果中排除:

var parentIds = db.Records
                .Where(r => r.ParentRecordId != null)
                .Select(r => r.ParentRecordId)
                // this ToList call may increase performance. Depending 
                // on the size of the result set we may not want to call
                // the database every time for this info
                .ToList();
var wantedRecords = from r in db.Records
                    where !parentIds.Contains(r.RecordId)
                    select r;