Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i explain this code?

Tags:

c#

linq

in .net, it is possible to write:

(from n in numbers where n == 5 select n).ToList();

without those brackets, it is not possible to call the ToList() method. how can i explain to someone what this line does (all i can say is it precompiles the query, but i do not know if this is actually 100% correct).

like image 617
GurdeepS Avatar asked Dec 06 '22 01:12

GurdeepS


1 Answers

from n in numbers where n = 5 select n is actually syntactic sugar for numbers.Where(n => n == 5). So you are filtering the list of numbers to those which equal 5 using a LINQ expression.

LINQ, however, evaluates lazy. That means that the object returned by numbers.Where(n => n == 5) (an IEnumerable) is not the list of numbers equaling five. The list is created only when needed, i.e., when trying to access the elements of the IEnumerable.

ToList copies the contents of this IEnumerable into a list, which means that the expression has to be evaluated right now.

like image 113
Heinzi Avatar answered Dec 08 '22 12:12

Heinzi