C# Interview Question #43
What is deferred execution in LINQ?
LINQ & Querying Mid-Level Intermediate
Quick Interview Answer
Deferred execution means a LINQ query is defined first but is not necessarily executed immediately. Execution occurs when the result is enumerated, for example by foreach, ToList, ToArray, First, Count, or another terminal operation.
Detailed Explanation
Deferred execution means a LINQ query is defined first but is not necessarily executed immediately. Execution occurs when the result is enumerated, for example by foreach, ToList, ToArray, First, Count, or another terminal operation.
This can improve efficiency because query operations can be composed before execution. However, it also means changes to the underlying collection may affect later enumeration.
With Entity Framework Core, deferred execution is especially important because the SQL query is normally sent to the database only when the IQueryable is materialized.
Code Example
var query = products.Where(p => p.IsActive);
// Query executes/enumerates here:
var result = query.ToList();