我正在使用实体框架生成一个查询,该框架使用 group by 子句,然后尝试对每个组进行排序以获取特定数据。我试图优化 order by 只发生一次使用 let 语句,但结果不正确,但查询仍然执行。
概念:
var results =
(from n in noteEntities.NoteLog
where associatedIDs.Contains(n.AssociatedID)
group n by n.AssociatedID into gn
let ogn = gn.OrderByDescending(t => t.CreatedDateTime)
let successNote = ogn.FirstOrDefault(x => x.Type == "Success")
let lastStatusNote = ogn.FirstOrDefault()
select new { Success = successNote, Status = lastStatusNote, AssociatedID = gn.Key }).ToList();
但是,问题在于,在随后的 let 语句中使用有序的 let 变量应该是什么,ogn
而不是使用降序排列的顺序,并且我得到了错误的成功和状态说明。我也尝试过更改内容以创建子查询并引用结果,但这似乎也没有返回有序列表,例如:
var subQuery =
(from n in noteEntities.NoteLog
where associatedIDs.Contains(n.AssociatedID)
group n by n.AssociatedID into gn
select gn.OrderByDescending(t => t.CreatedDateTime));
var results =
(from s in subQuery
let successNote = s.FirstOrDefault(x => x.Type == "Success")
let lastStatusNote = s.FirstOrDefault()
select new { Success = successNote, Status = lastStatusNote }).ToList();
我可以通过在 select 语句中使用 OrderByDescending 两次或让语句用于成功和状态注释来完成这项工作,但是当有很多注释时,这会变得非常缓慢且多余。有没有办法只运行一次订单并获得正确的结果?