如果where
条件没有返回任何结果,如何将缺省值插入返回的集合?如果查询没有返回任何东西,linq select item的默认值
from i in data.collection
where i.Type == type
select i.Count
如果where
条件没有返回任何结果,如何将缺省值插入返回的集合?如果查询没有返回任何东西,linq select item的默认值
from i in data.collection
where i.Type == type
select i.Count
使用Enumerable.DefaultIfEmpty
方法来做到这一点。
例(在方法的语法,因为它恕我直言不太尴尬):
data.collection.Where(i => i.Type == type)
.DefaultIfEmpty(defaultObject)
.Select(i => i.Count);
您正在寻找DefaultIfEmpty
。
var itemCounts = from i in data.collection
where i.Type == type
select i.Count;
var itemCountsOrMinusOne = itemCounts.DefaultIfEmpty(-1);
第一个会给你的项目计数,或IEnumerable
,返回没有元素。
第二会给你的项目数,或IEnuemrable
,只是返回-1
。
还有DefaultIfEmpty()方法。
在该方法中的语法,则可以使用这样的:
data.Collection
.Where(i => i.Type == type)
.DefaultIfEmpty(yourDefaultValue)
.Select(i => i.Count);
如果Where
过滤器返回没有物品,包含一项的可枚举与yourDefaultValue
被用作Select
投影的输入。
为什么你需要一个默认项目?一个空集合在这里很有意义。 – Rawling
我需要得到'0'为每个返回的空结果 –
我必须同意Rawling ...一个零计数序列将是明显的候选人在这里,除非类型使它以某种方式独特 –