So it is my understanding that LINQ does not execute everything immediately, it simply stores information to get at the data. So if you do a Where
, nothing actually happens to the list, you just get an IEnumerable
that has the information it needs to become the list.
One can 'collapse' this information to an actual list by calling ToList
.
Now I am wondering, why would the LINQ team implement it like this? It is pretty easy to add a List
at each step (or a Dictionary
) to cache the results that have already been calculated, so I guess there must be a good reason.
This can be checked by this code:
var list = Enumerable.Range(1, 10).Where(i => {
Console.WriteLine("Enumerating: " + i);
return true;
});
var list2 = list.All(i => {
return true;
});
var list3 = list.Any(i => {
return false;
});
If the cache were there, it would only output the Enumerating: i
once for each number, it would get the items from the cache the second time.
Edit: Additional question, why does LINQ not include a cache option? Like .Cache()
to cache the result of the previous enumerable?
Enumerable.Range(1, 10).ToList();
if you need to iterate over the list more than once. – Peter Bons May 25 '16 at 13:01