Single(), SingleOrDefault(), First() and FirstOrDefault() are extension methods of the Enumerable class.
Many people get confused about the difference between Single, SingleOrDefault, First, and FirstOrDefault methods in Linq. Let’s understand the difference between all these methods as below:
|Description||Returns a single, specific element of a sequence||Returns a single, specific element of a sequence, or a default value if that element is not found||Returns the first element of a sequence||Returns the first element of a sequence, or a default value if no element is found|
|Exception thrown when||There are 0 or more than 1 elements in the result||There is more than one element in the result||There are no elements in the result||Only if the source is null (they all do this)|
|When to use||If exactly 1 element is expected; not 0 or more than 1||When 0 or 1 elements are expected||When more than 1 element is expected and you want only the first||When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty|
I hope you will enjoy the LINQ Single vs SingleOrDefault vs First vs FirstOrDefault methods. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome