Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Linq, what's the difference between .FirstOrDefault and .SingleOrDefault

I don't know the difference between FirstOrDefault and SingleOrDefault. When should I use the first and when should I use the second?

like image 751
ridermansb Avatar asked Oct 05 '11 14:10

ridermansb


Video Answer


2 Answers

FirstOrDefault() is for when zero or more results are expected to be present in the input collection and the call returns the first item if there are multiple results, Default if none.

SingleOrDefault() is for when zero or one result is expected in the input collection and the call returns the one result if exactly one result is present, Default if no results and exception if more than one result.

like image 184
Bala R Avatar answered Sep 18 '22 14:09

Bala R


SingleOrDefault will throw a "Sequence contains more than one element" exception if more than one item exists.

like image 32
JontyMC Avatar answered Sep 17 '22 14:09

JontyMC