How can I explain this code?

in.net, you can write:

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

without these brackets, you cannot call the ToList () method. how can I explain to someone what this line is doing (all I can say is precompiling the request, but I don’t know if this is really 100% correct).

+4
source share
8 answers

It looks like a LINQ expression enclosed in parentheses, which results in an IEnumerable<int> , followed by a call to the extension method IEnumerable<T> ToList<T>() .

I think that in this case, calling ToList<T> causes the expression to be evaluated immediately, essentially rejecting the evaluation from laziness.

Eric White wrote a good article on Lazy (and Eager) Evaluation with LINQ

+1
source

from n in numbers where n = 5 select n is actually the syntactic sugar for numbers.Where(n => n == 5) . This way you filter a list of numbers equal to 5 using the LINQ expression.

LINQ, however, appreciates the lazy. This means that the object returned by numbers.Where(n => n == 5) (IEnumerable) is not a list of numbers equal to five. The list is created only when necessary, that is, when trying to access IEnumerable elements.

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

+6
source

The brackets are that for the parser, which can be .ToList() , only n can be used.

+5
source

In LINQ, by default, all queries are lazy. That is, until your collection is listed, the request itself has been analyzed, but not started.

ToList () forces to list the number of "numbers" of the collection and the request is executed.

+2
source

It converts from IEnumerable<t> to List<t>

+1
source

It may be easier for you to explain to someone unfamiliar with LINQ if you modify it to use extension methods directly.

 numbers.Where(number => number == 5).ToList(); 

This becomes much more obvious for a simple case like this.

+1
source

Someone familiar with LINQ may fix me, but I understand that the LINQ expression itself is not necessarily evaluated until you do something with it. Therefore, if you want it to be evaluated immediately, you would call ToList () as such. (Which also converts it from IEnumerable to IList, rather than just evaluating it.)

It is enclosed in parentheses, of course, to tell the compiler the fullness of what ToList () 'ed is.

0
source

Expressions in parentheses express a logical atomic value.

This is similar to arithmetic.

1 + 1 * 2 = 4 NO! (= 3)

(1 + 1) * 2 = 4 YES!

0
source

All Articles