Immediate vs Deferred Query Execution in LINQ

Immediate Query Execution: It executes the LINQ query just after the preparation of that query using extension methods; even any instance created after that.
 
Deferred Execution: It first prepares the LINQ query and then executes that query but if any instance is created after preparation then will impact on that query.
 
To understand the Immediate and Deferred query execution in detail, we need to create a class named "MyClass" that has some properties like ID (int Type) and Name (string Type).

Create a class

Deferred Query Execution

Until the created object is iterated the LINQ query will not fire or execute against the database. Use the following procedure to create a sample to explain it.
  1. We will create some instances of the preceding class as an array and store that into a var type variable named "lst".
  2. Then, filter the data (like ID, Name) from "lst" into a query variable named "Result" that you want to show.
  3. Iterate the "Result" variable to see the output one by one.

 Deferred Query Execution

To get the output of this, run the following example.
 
output

Question: Are you thinking that the query executed at the time of Step 2 from above?

Answer: No, the query will be executed at the time of Step 3, in other words iteration via the "foreach" loop. To prove this statement create 2 more instances of "MyClass" and add it to the "lst" variable.

lst.Add(new MyClass { ID = 8, Name = "H" });
lst.Add(new MyClass { ID = 9, Name = "I" });
 
List Code

To get the output of this, run the example:

Run to get the output

Now it has been proven that the query has been prepared only before iteration and executed at the time of iteration.

Immediate Query Execution
 
We can do this execution when the query is being created and use extension methods like "Count" or "ToList" and so on.

Add the "ToList" extension method to perform the Immediate Query Execution.

ToList extension method

See the results as in the following:

results
 
It gives the 7 records even after adding 2 instances in the "lst" variable because "ToList" executes the query just after preparation of the query and was not impacted by the 2 new instances.

Up Next
    Ebook Download
    View all
    Learn
    View all