Difference Between Deferred And Immediate Query Execution In LINQ

Deferred Query Execution

In .NET when you write a LINQ query it actually performs the querying only when the LINQ result is accessed. This phenomenon of LINQ is called deferred execution. One thing you should be aware of is that on every access of the result set the query gets executed again and again.

Example

  1. public void myCollection(List < int > myParentCollection) {  
  2.     //Deffered Query Execution. Without .ToList() this LINQ query will be executed twice.  
  3.     var childCollection = myParentCollection.Where(number => number > 100);  
  4.     Console.WriteLine(childCollection.Count()); //It will execute the childCollection Query first time.  
  5.     Console.WriteLine(childCollection.Average()); //It will execute the childCollection Query second time.  

Immediate Query Execution

To avoid the repeated execution, convert the LINQ result to List upon execution as shown below.

  1. public void myCollection(List < int > myParentCollection) {  
  2.     //Immediate Query Execution. Which is useful for caching query results and execute only once.  
  3.     var childCollection = myParentCollection.Where(number => number > 100).ToList(); //It will execute the childCollection Query here(only once).  
  4.     Console.WriteLine(childCollection.Count());  
  5.     Console.WriteLine(childCollection.Average());  
  6. }  

The basic difference between a Deferred execution vs Immediate execution is that Deferred execution of queries produce a sequence of values, whereas Immediate execution of queries return a singleton value and are executed immediately. Examples are using Count(), Average(), Max() etc.

Happy Coding... 

Next Recommended Reading Using LINQ to Query a DataSet