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?
Use Single / SingleOrDefault() when you sure there is only one record present in database or you can say if you querying on database with help of primary key of table. Developer may use First () / FirstOrDefault() anywhere, when they required single value from collection or database.
When you want a default value is returned if the result set contains no record, use SingleOrDefault. When you always want one record no matter what the result set contains, use First or FirstOrDefault. When you want a default value if the result set contains no record, use FirstOrDefault.
The major difference between First and FirstOrDefault is that First() will throw an exception if there is no result data for the supplied criteria whereas FirstOrDefault() will return the default value (null) if there is no result data.
SingleOrDefault<TSource>(IEnumerable<TSource>, TSource)Returns the only element of a sequence, or a specified default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
If your result set returns 0 records:
SingleOrDefault
returns the default value for the type (e.g. default for int is 0)FirstOrDefault
returns the default value for the typeIf you result set returns 1 record:
SingleOrDefault
returns that recordFirstOrDefault
returns that recordIf your result set returns many records:
SingleOrDefault
throws an exceptionFirstOrDefault
returns the first recordConclusion:
If you want an exception to be thrown if the result set contains many records, use SingleOrDefault
.
If you always want 1 record no matter what the result set contains, use FirstOrDefault
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With