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
- public void myCollection(List < int > myParentCollection) {
-
- var childCollection = myParentCollection.Where(number => number > 100);
- Console.WriteLine(childCollection.Count());
- Console.WriteLine(childCollection.Average());
- }
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) {
-
- var childCollection = myParentCollection.Where(number => number > 100).ToList();
- 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 are executed immediately. Examples are using Count(), Average(), Max() etc.
Happy Coding...