What is meant by "Linq evaluates query one method at a time"?
I've read somewhere that "Linq evaluates query one method at a time". What exactly is it meant by that? Perhaps that operators are called in the order specified – for example, in the following code Select
is called before Where
:
var results = someCollection.Select(...).Where(...);
while here Where
is called before Select
:
var results = someCollection.Where(...).Select(...);
Is this 开发者_StackOverflow社区what is meant by "evaluating query one method at a time"?
Thank you
Without a citation that tells us exactly where you read that, we can only guess at the meaning.
I would interpret that phrase to mean that multiple LINQ methods act as a pipeline, i.e. each piece of data flows through before the next one does.
For example:
var numbers = new[] { 1, 2, 3 };
var results = numbers.Select(number => number * 2).Where(number => number > 3);
With eager evaluation, the execution would look like this:
1, 2, 3 -> Select -> 2, 4, 6 -> Where -> 4, 6
However, with deferred evaluation, each result is calculated when it is needed. This turns the execution of the methods "vertical" instead of "horizontal", executing all methods for each data item, then starting again with the next data item:
1 -> Select -> 2 -> Where -> nothing
2 -> Select -> 4 -> Where -> 4
3 -> Select -> 6 -> Where -> 6
Of course, this is not true for methods which operate on the whole set, such as Distinct
and OrderBy
. All of the data items must "pool" there until execution can continue. For the most part, though, LINQ methods only ask for items from the source when they themselves are asked for another item.
精彩评论