Header Ads

LINQ - First() vs FirstOrDefault() and Single() vs SingleOrDefault()

Many people get confused about the difference between First vs FirstOrDefault and Single vs Single OrDefault methods in LINQ. Let me explain below difference between them.
LINQ


First() FirstOrDefault() Single()SingleOrDefault()
DescriptionReturns the first element of a sequenceReturns the first element of a sequence, or a default value if no element is foundReturns a single, specific element of a sequenceReturns a single, specific element of a sequence, or a default value if that element is not found
Exception thrown whenThere are no elements in the resultOnly if the source is null (they all do this)There are 0 or more than 1 elements in the resultThere is more than one element in the result
When UseWhen more than 1 element is expected and you want only the firstOnly if the source is null (they all do this)If exactly 1 element is expected; not 0 or more thanWhen 0 or 1 elements are expected

No comments:


Powered by Blogger.