LINQ Interview Question #81

What happens if the source collection changes before a deferred query is executed?

Deferred Execution, Immediate Execution & Query Behavior Mid-Level Intermediate

Quick Interview Answer

A deferred query normally reads the source when it is enumerated, not when the query variable is created. Therefore, changes made before enumeration can affect the results.

Detailed Explanation

A deferred query normally reads the source when it is enumerated, not when the query variable is created. Therefore, changes made before enumeration can affect the results.

If a snapshot is required, materialize the query with ToList, ToArray, or another suitable operation at the desired point in time.

Code Example

var numbers = new List<int> { 1, 2, 3 };

var query = numbers.Where(n => n > 1);

numbers.Add(4);

var result = query.ToList();
// 2, 3, 4