Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need Single() in LINQ?

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.

like image 800
Oscar Mederos Avatar asked May 14 '11 20:05

Oscar Mederos


People also ask

What is single () in C#?

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.

What is difference between single and default in LINQ?

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.

What is the difference between single () and SingleOrDefault () if no elements are found?

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.

What is single or default?

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.


1 Answers

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.

like image 57
JaredPar Avatar answered Oct 07 '22 19:10

JaredPar