.Net

LINQ Single vs SingleOrDefault vs First vs FirstOrDefault

SINGLE()SINGLEORDEFAULT()FIRST()FIRSTORDEFAULT()
DESCRIPTION Returns a single, specific element of a sequenceReturns a single, specific element of a sequence, or a default value if that element is not foundReturns the first element of a sequenceReturns the first element of a sequence, or a default value if no element is found
EXCEPTION THROWN There are 0 or more than 1 elements in the resultThere is more than one element in the resultThere are no elements in the resultOnly if the source is null (they all do this)
WHEN TO USEIf exactly 1 element is expected; not 0 or more than 1When 0 or 1 elements are expectedWhen more than 1 element is expected and you want only the firstWhen more than 1 element is expected and you want only the first. Also it is ok for the result to be empty

Single()SingleOrDefault()First() and FirstOrDefault() are extension methods of the Enumerable class.

Related Articles

Leave a Reply

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

Back to top button

Adblock Detected

Please consider supporting us by disabling your ad blocker