LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria
Asked 07 September, 2021
Viewed 2.1K times
  • 51
Votes

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?

16 Answer