Programming Languages

LINQ Deferred Execution: When Does This Query Read the List?

Huwell Consultancy editorial2 min read

Defining a LINQ query does not always mean its results have already been calculated. Some operations wait until the sequence is enumerated. Understanding the timing helps explain results that seem to change unexpectedly.

Try an in-memory example

var numbers = new List<int> { 1, 2 };
var query = numbers.Where(n => n > 1);
numbers.Add(3);
Console.WriteLine(string.Join(", ", query));

For this LINQ-to-Objects example, the output is 2, 3. The Where query is enumerated after the list changes. Microsoft describes deferred execution as delaying evaluation until the value is needed. This example does not imply that every LINQ operator or provider behaves identically.

Compare a materialised result

Change the query assignment to numbers.Where(n => n > 1).ToList() before adding 3. The resulting list contains 2. You have materialised those results at that point. That is different from promising a deep copy of every object a query might return.

Ask three timing questions

  • When is the query defined?
  • When is it enumerated?
  • Can the source change between those points?

Use the distinction in practice

Repeated enumeration may repeat work, so understand the source before choosing how to consume it. Do not add ToList everywhere without considering memory and intended behaviour. In a Malta .NET interview, walk through the order of statements and predict the result. A tiny example often reveals more understanding than a broad claim that LINQ is always lazy.

Sources and further reading

Browse current technology jobs in Malta →

EXPLORE THE NEXT STEP

Discuss the work you want to do.

Browse current technology vacancies with Huwell Consultancy and ask us about the responsibilities that matter to you.

Explore opportunities
KEEP EXPLORING

More guidance for your next decision