Reputation: 17045
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?
Upvotes: 0
Views: 1633
Reputation: 245389
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.
Upvotes: 4
Reputation: 43067
Use FirstOrDefault
if you want the first matching item or null if there are none.
var myVar2 = myCollection.FirstOrDefault(q => q.Id == 10);
Upvotes: 7