LINQ Max扩展方法在空集合上给出错误 [英] LINQ Max extension method gives an error on empty collections
本文介绍了LINQ Max扩展方法在空集合上给出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下查询:
var maxNumber = dbContext.Where(a => a.Id == 9).Max(a => a.Sample_Num);
如果没有编号为9的ID,则会出现错误.如果没有ID为9,我想将结果默认为0.
If there is no Id of 9, I get an error. I like to default the result to 0 if there is no Id of 9.
我尝试过:
var maxNumber = dbContext.Where(a => a.Id == 9).Max(a => a.Sample_Num) ?? 0;
以及其他变体,但无法使其正常工作
as well as other variations but was not able to get it to work
推荐答案
您可以使用Any
检查是否存在匹配的元素:
You could use Any
to check if there's a matching element:
int maxNumber = 0;
var id9 = dbContext.Where(a => a.Id == 9);
if(id9.Any())
{
maxNumber = id9.Max(a => a.Sample_Num);
}
,或者您可以使用 DefaultIfEmpty(defaultValue)
:
or you could use DefaultIfEmpty(defaultValue)
:
int maxNumber = dbContext
.Where(a => a.Id == 9)
.Select(a => a.Sample_Num)
.DefaultIfEmpty(0)
.Max();
这篇关于LINQ Max扩展方法在空集合上给出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文