Nov 11, 2012

Deferred vs Immediate Query Execution in LINQ

1 comment
In LINQ, queries have two different behaviors of execution,
   1. Immediate
   2. Deferred

Here we will check how Deferred and Immediate Query Executions works in LINQ.

Deferred Query Execution
To understand Deferred Query Execution, let’s take the example which declares few Orders and then retrieve all orders related to CustomerID = 84.

Above program gives us the output as : 1,3

Looking at the query shown above, it appears that the query is executed when the query variable is created(Shown in RED box is). However that’s not true. The query is actually executed when the query variable(results) is iterated over. This is called deferred execution.

Now how to prove that, the query was not executed when the query variable is created? It’s simple. Just add another Order to the Orders list after the query variable is created.

Observe that, we are adding new Order to list after the query variable is created. In this scenario if the query is executed when the query variable is created, the results should be the same as the one we got earlier, i.e. only two orders would meet the criteria.

But the output is not the same as query is executed while iterating through the query variable in foreach loop.

Above program gives us the output as: 1,3,4

This allows us to execute a query as frequently as we want to, like fetching the latest information from a database that is being updated frequently by other applications.

Immediate Query Execution
We can also force a query to execute immediately, which is useful for caching query results. For example we want to display a number of Order that match a criteria.

In the query shown above, in order to count the elements that match the condition, the query must be executed, and this is done automatically when Count( ) is called. So adding a new ORDER instance after the query variable declaration does not have any effect.

To force immediate execution of a query that does not produce a single value, we can call the ToList(), ToDictionary() or ToArray() method on a query or query variable. These are called conversion operators, which allow us to make a copy of the result and access those as many times as we need, without the need to re-execute the query.

If you feel this is helpful or you like it, Please share this using share buttons available on page.

1 comment :