Single vs SingleOrDefault vs First vs FirstOrDefault

Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  

When to use Single, SingleOrDefault, First and FirstOrDefault

You should take care of following points while choosing Single, SingleOrDefault, First and FirstOrDefault:

  1. When you want an exception to be thrown if the result set contains many records, use Single or SingleOrDefault.
  2. When you want a default value is returned if the result set contains no record, use SingleOrDefault.
  3. When you always want one record no matter what the result set contains, use First or FirstOrDefault.
  4. When you want a default value if the result set contains no record, use FirstOrDefault.

Perfomance of SingleOrDefault and FirstOrDefault

FirstOrDefault usually perform faster as compared SingleOrDefault, since these iterate the collection until they find the first match. While SingleOrDefault iterate the whole collection to find one single match.


Share the joy
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.