rem
rem

Reputation: 17045

"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?

Upvotes: 0

Views: 1633

Answers (2)

Justin Niessner
Justin Niessner

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

jrummell
jrummell

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

Related Questions