linq Benefits of deferred execution - building queries


Example

Deferred execution enables combining different operations to build the final query, before evaluating the values:

var list = new List<int>() {1,1,2,3,5,8};
var query = list.Select(x => x + 1);

If we execute the query at this point:

foreach (var x in query) {
    Console.Write($"{x} ");
}

we would get the following output:

2 2 3 4 6 9

But we can modify the query by adding more operators:

Console.WriteLine();
query = query.Where(x => x % 2 == 0);
query = query.Select(x => x * 10);

foreach (var x in query) {
    Console.Write($"{x} ");
}

Output:

20 20 40 60