How LINQ to Objects executes queries

suggest change

LINQ to Objects queries do not execute immediately. Building the query stores it for later. The query runs when something iterates it, for example foreach, or when a method needs the results, such as ToList, Count, Max, Average, or First.

This is considered deferred execution. This allows you to build up the query in multiple steps, potentially modifying it based on conditional statements, and then execute it later only once you require the result.

Given the code:

var query = from n in numbers 
            where n % 2 != 0
            select n;

The example above only stores the query in the query variable. It does not execute the query.

The foreach statement forces the query execution:

foreach(var n in query) {
    Console.WriteLine($"Number selected {n}");
}

Count, First, Max, and Average also run the query. They return a single value. ToList and ToArray run it and store the results in a List<T> or an array.

Be aware that it is possible for you to iterate across the query multiple times if you call multiple LINQ functions on the same query. This could give you different results at each call. If you only want to work with one data set, be sure to save it into a list or array.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents