The difference between Where and Single

I am trying to figure out the difference between Where (Expression) and Single (Expression).

Is the expression passed to one redirected to the Where function?

For example, are these two statements the same?

var result = context.Persons.Single(p => p.ID == 5);
var result2 = context.Persons.Where(p => p.ID == 5).Single();
+3
source share
2 answers

Singlereturns to you Person, while Wherereturns to you IEnumerable<Person>.

Passing the where clause to a single is just syntactic sugar.

Both lines are functionally equivalent. The first thing I guess may be so slightly more effective. In my opinion, it is also easier on the eye.

+5
source

. Single() , . , , , .

int[] a = {1, 2, 3};
var odd_Nos = a.Single(num => num % 2 != 0) // will throw exception (an InvalidOperationException)
var even_Nos = a.Single(num => num % 2 == 0) // will not throw exception

, , First() FirstOrDefault().

0

Source: https://habr.com/ru/post/1755467/


All Articles