.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.

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

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

Back to top button