C# LINQ: Deferred Query Execution vs Immediate Execution

Updated on     Kisan Patel

The LINQ query only stores query commands. When you define a query in LINQ during runtime, the query does not run. The query actually runs when you request the data. Therefore, the actual execution of LINQ  query is held back until the request for the data is made by you. This concept of holding back the actual execution is termed as deferred query execution.

You can use the foreach statement to  retrieve the LINQ query results. For example, in a database that is updated continuously, you can create a LINQ query that retrieves the latest data, and you can also execute it repeatedly at different intervals to retrieve different results every time.

The following example shows how query execution is deferred until the query is enumerated at a foreach statement.

int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 

var q = from n in numbers 
        select n;
foreach (var v in q) 
{ 
    Console.WriteLine(v);
}

The output of the above C# program…

Deferred-Execution

If the queries perform aggregation functions over a range of items, the query must first iterate over the range. This is called immediate execution. These functions must first iterate over the source elements and then display the result. The clauses that perform such kind of forced execution are Count, Max, Min, and Average. Unlike deferred execution, immediate execution of queries does not require an explicit foreach statement to return the result.

The following example shows how queries can be executed immediately with operators such as ToList().

int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var q = (from n in numbers
          select n).ToList();

foreach (var v in q)
{
    Console.WriteLine(v);
} 

If you compare deferred to immediate query execution, deferred query execution has an edge over the immediate query execution. This is because in deferred query execution the query does not hold the result and you can execute it as often as you like. You can also update the data source on a regular basis by a separate application. You can retrieve the latest data in deferred query execution. This kind of functioning is not possible in immediate query execution.


C# LINQ

Leave a Reply