[英]Linq Lambda group by get max
I like to get the Max Sample Num for where the Id is 9 我喜欢获得Id为9的Max Sample Num
var samplecount = dbContext.ChemDetails
.GroupBy(a => a.Id == 9)
.Select(a => a.Max(w => w.Sample_Num))
.FirstOrDefault();
What I am getting from above is the max, not from where Id == 9. 我从上面得到的是最大值,而不是Id == 9。
You just need a Where
clause, then take the max: 你只需要一个Where
子句,然后取最大值:
var maxNumber = dbContext.Where(a => a.Id == 9).Max(a => a.Sample_Num);
If you wanted to get the max value for each Id
, that's when you'd use GroupBy
. 如果您想获得每个Id
的最大值,那就是您使用GroupBy
。
Dictionary<int,int> MaxLookup = dbContext.ChemDetails
.GroupBy(a => a.Id)
.ToDictionary(g => g.Key, g => g.Max(item => item.Sample_Num));
int maxForId9 = 0;
if (MaxLookup.ContainsKey(9)) maxForId9 = MaxLookup[9];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.