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.

0 0 votes
Article Rating

Do you want to hire us for your Project Work? Then Contact US.
Spread the love
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x