Tuesday, March 24, 2015

LINQ : Single, SingleOrDefault, First and FirstOrDefault

Single

Returns a single specific element from a collection of elements when element match found. An exception is thrown, when none or more than one match found for that element in the collection.

SingleOrDefault

Returns a single specific element from a collection of elements when element match found. An exception is thrown, when more than one match found for that element in the collection. A default value is returned, when no match is found for that element in the collection.

First

Returns first specific element from a collection of elements when one or more than one match found for that element. An exception is thrown, when no match is found for that element in the collection.

FirstOrDefault

Returns first specific element from a collection of elements when one or more than one match found for that element. A default value is returned, when no match is found for that element in the collection.

When to use Single, SingleOrDefault, First and FirstOrDefault


  1. If you want an exception to be thrown if the result set contains many records, use Single or SingleOrDefault.
  2. If you want a default value is returned if the result set contains no record, use SingleOrDefault.
  3. If you always want one record no matter what the result set contains, use First or FirstOrDefault.
  4. If 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 it's iterate the collection until they find the first match. While SingleOrDefault iterate the whole collection to find one single match.