Operator |
If the source sequence is empty |
The source sequence consists of only one element |
The source sequence contains multiple elements |
First |
Throw exception |
Returns the element |
Returns the first element |
FirstOrDefault |
Return to Default (TSource) |
Returns the element |
Returns the first element |
Last |
Throw exception |
Returns the element |
Returns the last element |
LastOrDefault |
Return to Default (TSource) |
Returns the element |
Returns the last element |
Single |
Throw exception |
Returns the element |
Throw exception |
Singleordefault |
Return to Default (TSource) |
Returns the element |
Throw exception |
Obviously, if the input sequence has only one element, the execution results of these operators are very consistent:) Similarly, if the input sequence is empty, then the operator without "Ordefault" throws an exception (InvalidOperationException) with "Ordefault" operator returns the default value of the element type (the default value for the reference type is Null,int, 0, and so on).
If the input sequence (possibly filtered) contains multiple elements, the results of the execution of these operators differ greatly, and the result of first and last is the name, and single throws an exception. It is important to note that Singleordefault also throws an exception because it does not look like this: if the input sequence has only one element, the element is returned, otherwise the default value is returned. If you need an operator that can handle a multi-element sequence, use first or last. If you need to deal with sequences that may be empty, use FirstOrDefault or LastOrDefault. Note that if you use an operator with "Ordefault", then an empty sequence and a sequence with only the default values will perform exactly the same.
The difference between First,firstordefault,single,singleordefault