[英]Linq select latest in group hierarchy
I want to get the latest record for each group if records when self-referencing hierarchy exists. 如果存在自引用层次结构的记录,我想获取每个组的最新记录。
My table looks like this: 我的表看起来像这样:
RecordId CreatedDate ParentRecordId
1 2012/05/13 NULL
2 2012/05/13 NULL
3 2012/05/14 1
4 2012/05/15 3
I want to select only latest versions of records. 我想只选择最新版本的记录。
So in this case I only want to select RecordId = 2 and RecordId =4. 所以在这种情况下我只想选择RecordId = 2和RecordId = 4。
Here's what I have so far and I'm stuck. 这就是我到目前为止所遇到的问题。
db.Records
.Where(x => x.ParentRecordId!= null).GroupBy(x => x.ParentRecordId)
.SelectMany(x=>x.OrderByDescending(y=>y.CreatedDate).Take(1)).ToList();
My left joins are a bit lacking, but something like this ought to do it; 我的左连接有点缺乏,但这样的事情应该这样做;
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;
How about a query that answers "Get all entries for which there is not another entry that considers me a parent". 查询如何回答“获取没有其他条目认为我是父母的所有条目”。 That sounds like the same thing, unless I misunderstand:
这听起来像是一回事,除非我误解:
db.Records.Where(x => !db.Records
.Select(r => r.ParentRecordId).Contains(x.RecordId))
However, I'm a little confused on what you mean by "circularity". 但是,我对“圆形”的意思有点困惑。 How can a hierarchy be circular?
层次结构如何成为循环?
you should get a list of the ParentRecordId
s first, and then check to see if the RecordId
is in that list, if it is then we should exclude it from the results: 你应该首先获得
ParentRecordId
的列表,然后检查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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.