linq Method execution modes - immediate, deferred streaming, deferred non-streaming Benefits of deferred execution - querying current data

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.Clear();
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



Got any linq Question?