Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Single LINQ extension method create a query Select TOP(2)?

I was looking at my profiler and it seem that the Linq extension method Single selects 2 rows. So why does the Single LINQ extension method create a query Select TOP(2)? Shouldn't it be select top(1) instead?

like image 838
Rushino Avatar asked Jan 12 '12 02:01

Rushino


People also ask

What is the use of single in LINQ?

In LINQ, the Single() method is used to return the single element from the collection, which satisfies the condition. In case, if the Single() method found more than one element in collection or no element in the collection, then it will throw the "InvalidOperationException" error.

What is LINQ extension method?

Linq provides standard query operators like filtering, sorting, grouping, aggregation, and concatenations, and it has many operators to achive many types of functionalities, which are called extension methods, in LINQ.

How does Select work in LINQ?

Select is used to project individual element from List, in your case each customer from customerList . As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of Salary property from Customer class.


1 Answers

First only requests a single result. Single requests two results because it only returns a result if there is exactly one member of the result set. If there are zero or two (or more than two) it throws an exception, so it has to request at least two results.

like image 112
Gabe Avatar answered Oct 25 '22 08:10

Gabe