[英]How to use Max and Group By in LINQ
I try to use this line: 我尝试使用此行:
return ObjectContext.TH_Proposal.GroupBy.where(/* condition*/).(y => y.ProposalID).Max(y =>y.ProposalDate);
I want a result like this using LINQ 我想要使用LINQ这样的结果
select *
from TH_Proposal
where ProposalDate in (select max(ProposalDate)from TH_Proposal group by ProposalID)
You can do it like this: 您可以这样做:
ObjectContext.TH_Proposal.GroupBy(
p => p.ProposalID,
(id, g) => g.OrderByDescending(p => p.ProposalDate).First());
This groups the entries by ProposalID
and selects the one with the highest ProposalDate
. 这
ProposalID
对条目进行分组,并选择具有最高ProposalDate
的条目。
This is much easier in Linq than SQL since Linq can take the first item of each group: 在Linq中,这比SQL容易得多,因为Linq可以采用每个组的第一项:
return
ObjectContext.TH_Proposal
.OrderBy(y => y.ProposalDate)
.GroupBy(y => y.ProposalID)
.Select(g => g.First());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.