linq Benefits of deferred execution - querying current data


With deferred execution, if the data to be queried is changed, the query object uses the data at the time of execution, not at the time of definition.

var data = new List<int>() {2, 4, 6, 8};
var query = data.Select(x => x * x);

If we execute the query at this point with an immediate method or foreach, the query will operate on the list of even numbers.

However, if we change the values in the list:

data.AddRange(new [] {1, 3, 5, 7, 9});

or even if we assign a a new list to data:

data = new List<int>() {1, 3, 5, 7, 9};

and then execute the query, the query will operate on the new value of data:

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

and will output the following:

1 9 25 49 81