Deferred execution and caching of all elements using .ToList()are not the only parameters. The third option is to cache the elements , as you execute, using the lazy list.
Execution is still delayed, but all items are returned only once. An example of how this work:
public class LazyListTest
{
private int _count = 0;
public void Test()
{
var numbers = Enumerable.Range(1, 40);
var numbersQuery = numbers.Select(GetElement).ToLazyList();
var total = numbersQuery.Take(3)
.Concat(numbersQuery.Take(10))
.Concat(numbersQuery.Take(3))
.Sum();
Console.WriteLine(_count);
}
private int GetElement(int value)
{
_count++;
return value * 100;
}
}
If you run the Test () method, there _countwill only be 10. Without caching, it will be 16 s. ToList()it will be 40!
An example implementation of LazyList can be found here .
source
share