Consider the IEnumerable extension methods SingleOrDefault()
and FirstOrDefault()
MSDN documents that SingleOrDefault
:
Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
whereas FirstOrDefault
from MSDN (presumably when using an OrderBy()
or OrderByDescending()
or none at all),
Returns the first element of a sequence
Consider a handful of example queries, it's not always clear when to use these two methods:
var someCust = db.Customers
.SingleOrDefault(c=>c.ID == 5); //unlikely(?) to be more than one, but technically COULD BE
var bobbyCust = db.Customers
.FirstOrDefault(c=>c.FirstName == "Bobby"); //clearly could be one or many, so use First?
var latestCust = db.Customers
.OrderByDescending(x=> x.CreatedOn)
.FirstOrDefault();//Single or First, or does it matter?
Question
What conventions do you follow or suggest when deciding to use SingleOrDefault()
and FirstOrDefault()
in your LINQ queries?