Deffered 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:

 public void myCollection(List<int> myParentCollection)
{
            //Deffered Query Execution. Without .ToList() this LINQ query will be executed twice.
            var childCollection = myParentCollection.Where(number => number > 100);

            Console.WriteLine(childCollection.Count()); //It will execute the childCollection Query first time.
            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.

 public void myCollection(List<int> myParentCollection)
{
            //Immediate Query Execution. Which is useful for caching query results and execute only once.
            var childCollection = myParentCollection.Where(number => number > 100).ToList(); //It will execute the childCollection Query here(only once).

            Console.WriteLine(childCollection.Count()); 
            Console.WriteLine(childCollection.Average()); 
}

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 is executed immediately. Examples are using Count(), Average(), Max() etc.

 

Happy Coding… 🙂