Deferred ExecutionConsider this example below (Again our same old example which we are dealing in the whole series) Our custom class type (Student)
List of Students
Let’s add one more student after querying the students collection (and ordering them to descending) and see what the result will look while iterating the result as shown below
As you can see above, I am adding a student named Jacob after querying the students collection
Now you might wonder, how this has happened, since we added Jacob only after query execution, where the descending order operation might have already taken place, but still how come the students are correctly ordered based on their StudID, the answer is Deferred Execution behavior of LINQ. Since the execution of LINQ query does not takes place while you do the query, but the actual execution happens while you do Iteration. Hence deferred execution can be better described as
“LINQ Query execution happens only during iteration, rather during query declaration, this execution behavior of LINQ is called as Deferred Execution”As you can see below, instead of 5 records, LINQ query initially taken 6 (Adding the new value)
Immediate ExecutionHere we are going to convert our query to List (remember we already discussed about ToList in Conversion methods in LINQ) Hence our code looks like this
But let’s see what the output
Well wait, what happened to Jacob, do you see the newly added student here, NO. We will see what happened to our student behind the scene by debugging the code.
As you can see from the above code execution, the StudM implicitly typed variable type has got only 5 records, but in the Deferred execution we had 6 records and that’s the reason we couldn’t see our newly added record (Jacob) in immediate execution, whereas the opposite happened in deferred execution.