Even though Select operator gets called before the Take operator, the lambda expression will only get called for the first two input elements:
string[] count = { "one ", "two ", "three ", "four ", "five ", "six " };
IEnumerable<int> results = count.Select(item =>
{
Console.WriteLine(item);
return item.Length;
}).Take(2);
foreach (int i in results);
OUTPUT:
one two
a) Assuming we chain several Linq-to-Objects standard query operators together, is the order in which Take operator gets called never important? Thus, it never matters whether Take gets called first or last, since the number of input elements for which the lambda expression will be called is always the same?
b) Again assuming we chain several Linq-to-Objects standard query operators together, are there any other Linq-to-Objects operators where the order in which they are called doesn’t affect the number of input elements for which the lambda expression gets called?
Thank you
Query operators typically only move as many steps forward in the source collection as they need to produce the number of required output results.
In your example
Take()will only require 2 items fromSelect()so that’s all that will be produced bySelect().Select()is probably implemented roughly like this (taken from Jon Skeet’s blog:Sorting and grouping operators will need to create the full result set before being able to return anything (e.g.
OrderBy()).As long as you don’t use any ordering, grouping, filtering (such as with
Where()orSkip()) or any other operator changing the number of items in the sequence it shouldn’t matter where in the chain you put theTake().