[英]“Sequence contains no matching element ” instead of just null
The myCollection
contains no element with Id == 10
: myCollection
包含Id == 10
元素:
var myVar1 = myCollection.Where(q => q.Id == 10);
In the above case the myVar1
represents just the empty collection. 在上述情况下, myVar1
仅代表空集合。
But why in the following example I get a Sequence contains no matching element exception instead of just null
in the myVar2
? 但是,为什么在下面的示例中,我得到一个不包含匹配元素异常的Sequence,而在myVar2
中不包含 null
呢?
var myVar2 = myCollection.First(q => q.Id == 10);
How to explain it correctly? 如何正确解释?
如果要第一个匹配项,请使用FirstOrDefault
如果没有,请使用null。
var myVar2 = myCollection.FirstOrDefault(q => q.Id == 10);
Because First()
expects one and only one result to be returned. 因为First()
期望返回一个且只有一个结果。 It isn't meant to handle a one or no results. 这并不是要处理一个或没有结果。
You need FirstOrDefault()
for that. 为此,您需要FirstOrDefault()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.