简体   繁体   中英

“Sequence contains no matching element ” instead of just null

The myCollection contains no element with Id == 10 :

var myVar1 = myCollection.Where(q => q.Id == 10);

In the above case the myVar1 represents just the empty collection.

But why in the following example I get a Sequence contains no matching element exception instead of just null in the myVar2 ?

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. It isn't meant to handle a one or no results.

You need FirstOrDefault() for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM