Difference between FirstOrDefault, First, SingleOrDefault, and Single in C#
I see. Curiosity brings you here, right? So what’s the difference between those four enumerable methods? Here is what I found.
FirstOrDefault()
- Returns the first element of a sequence, or a default value if the sequence contains no elements.
- Will throw an error if the source is null
First()
- Returns the first element of a sequence.
- Will throw an error if the source is null
- Will throw an error if it didn't get any value from your query.
SingleOrDefault()
- Returns the only element of a sequence, or a default value if the sequence is empty.
- Will throw an error if the source is null or when the input sequence contains more than one element.
Single()
- Returns the only element of a sequence and throws an exception if there is not exactly one element in the sequence.
- Will throw an error if the source is null or when the input sequence contains more than one element.