Methods
First()
/FirstOrDefault()
vs Single()
/SingleOrDefault()
First()
/FirstOrDefault()
vs Single()
/SingleOrDefault()
These methods are used to retrieve a single element from a sequence.
The main difference between these methods is in how they handle cases where there are multiple matching elements in the sequence.
Single() / SingleOrDefault() | First() / FirstOrDefault() |
---|---|
If there are multiple matching elements, | If there are multiple matching elements, |
Single
/SingleOrDefault
is useful for cases where you know there should only be one matching element, and you want to ensure that the query doesn't return multiple results or no results at all.
In general, FirstOrDefault()
may be faster because it returns as soon as it finds the first matching element in the sequence, whereas SingleOrDefault()
checks to ensure that there is only one matching element and will continue to search the entire sequence even after finding a match.
Example
If there are no matching elements
If there are multiple matching elements
Conclusion
Use
FirstOrDefault
if you don't care how many items there are or when you can't afford checking uniqueness (e.g. in a very large collection). When you check uniqueness on adding the items to the collection, it might be too expensive to check it again when searching for those items.Use
SingleOrDefault
if you don't have to care about performance too much and want to make sure that the assumption of a single item is clear to the reader and checked at runtime.
Last updated