How LINQ to Object executes queries

suggest change

LINQ queries do not execute immediately. When you are building the query you are simply storing the query for future execution. Only when you actually request to iterate the query is the query executed (e.g. in a for loop, when calling ToList, Count, Max, Average, First, etc.)

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 into query variable. It does not execute the query itself.

The foreach statement forces the query execution:

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

Some LINQ methods will also trigger the query execution, Count, First, Max, Average. They return single values. ToList and ToArray collects result and turn them to a List or a Array respectively.

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