如果使用SingleOrDefault()并在数字列表中搜索不在列表中的数字,如何返回null? [英] How to return null if using SingleOrDefault() and searching a list of numbers for a number not in list?
本文介绍了如果使用SingleOrDefault()并在数字列表中搜索不在列表中的数字,如何返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用SingleOrDefault()
查询正数列表时,如果在列表中未找到数字而不是类型的默认值(本例中为0),如何返回空值或自定义值(如-1)情况)?
When querying a list of positive numbers using SingleOrDefault()
, how can I return null, or a custom value like -1, when a number isn't found in the list, instead of the type's default value (0 in this case)?
推荐答案
您可以使用DefaultIfEmpty
为空集合指定自定义默认值:
You can use DefaultIfEmpty
to specify a custom default value for an empty collection:
var value = numbers.Where(MyFilter)
.DefaultIfEmpty(-1) //or any other default value you want
.Single(); //OrDefault not needed; DefaultIfEmpty ensures there is an item
这篇关于如果使用SingleOrDefault()并在数字列表中搜索不在列表中的数字,如何返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文