LINQ Interview Question #22

What is deferred execution in LINQ?

LINQ Fundamentals, Syntax, IEnumerable & IQueryable Junior Beginner

Quick Interview Answer

Deferred execution means constructing a LINQ query does not necessarily execute it immediately. Many operators such as Where and Select return an object that represents the query, and the source is processed later when the result is enumerated.

Detailed Explanation

Deferred execution means constructing a LINQ query does not necessarily execute it immediately. Many operators such as Where and Select return an object that represents the query, and the source is processed later when the result is enumerated.

This enables query composition, but it also means repeated enumeration can repeat work or re-query a data source. Developers should understand when a query is actually materialized.

Code Example

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

// The sequence is evaluated when enumerated.
foreach (var number in query)
{
    Console.WriteLine(number);
}