Why is the main purpose of the extension method Single()?
I know it will throw an exception if more than an element that matches the predicate in the sequence, but I still don’t understand in which context it could be useful.
Edit:
I do understand what Single is doing, so you don’t need to explain in your question what this method does.
It’s useful for declaratively stating
There are many times when programs need to reduce a set of elements to the one that is interesting based an a particular predicate. If more than one matches it indicates an error in the program. Without the
Singlemethod a program would need to traverse parts of the potentially expensive list more once.Compare
To
The latter requires two statements and iterates a potentially expensive list twice. Not good.
Note: Yes
Firstis potentially faster because it only has to iterate the enumeration up until the first element that matches. The rest of the elements are of no consequence. On the other handSinglemust consider the entire enumeration. If multiple matches are of no consequence to your program and indicate no programming errors then yes useFirst.