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.
In C#, Single. IsNegativeInfinity(Single) is a Single struct method. This method is used to check whether a specified floating-point value evaluates to negative infinity or not. In some floating point operation, it is possible to obtain a result that is negative infinity.
Use Single() when you are sure that the query must return only one record, and use SingleOrDefault() when a query returns the only element from the sequence, or a default value if the sequence is empty.
The SingleOrDefault() method does the same thing as Single() method. The only difference is that it returns default value of the data type of a collection if a collection is empty, includes more than one element or finds no element or more than one element for the specified condition.
SingleOrDefault<TSource>(IEnumerable<TSource>, TSource)Returns the only element of a sequence, or a specified default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence.
It's useful for declaratively stating
I want the single element in the list and if more than one item matches then something is very wrong
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 Single
method a program would need to traverse parts of the potentially expensive list more once.
Compare
Item i = someCollection.Single(thePredicate);
To
Contract.Requires(someCollection.Where(thePredicate).Count() == 1);
Item i = someCollection.First(thePredicate);
The latter requires two statements and iterates a potentially expensive list twice. Not good.
Note: Yes First
is 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 hand Single
must consider the entire enumeration. If multiple matches are of no consequence to your program and indicate no programming errors then yes use First
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With