Skip to main content

LINQ - Deferred and Immediate Execution


LINQ - Deferred and Immediate Execution


LINQ Queries can be categorised based on execution behaviour.


Deferred Execution

The execution of an expression is delayed until its realized actual value is required. Deferred execution can be applied on an in-memory collection as well as remote LINQ providers like LINQ to SQL, LINQ to XML etc. 


It greatly improves performance by avoiding unnecessary execution. Deferred execution reevaluates on each execution which is called LAZY Evaluation. It always gives the latest data of the collection when executing.


Deferred or Lazy Operators - These query operators use deferred execution.

Examples - Select, where, Take, Skip

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
List<Student> Students = new List<Student>
{
    new student() { Id = 1, Name = "Mike" },
    new student() { Id = 2, Name = "Gracy" },
    new student() { Id = 3, Name = "Mitch" }
};
var numbers = from x in list
                        where x.id > 1
                        select x;

foreach(Student s in Students)       --> Query Executed here
    Console.Writeline(s.Name);

Students.Add(new Student() { Id = 4, Name = John };

foreach(Student s in numbers)       --> Query Executed again here and returns the latest data
    Console.Writeline(s.Name);

Output:

Gracy
Mitch

Gracy
Mitch
John

Immediate Execution

Immediate or Greedy Operators - These query operators use immediate execution.

Examples - count, average, min, max, ToList

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
List<Student>; Students = new List<Student>;
{
    new student() { Id = 1, Name = "Chandru" },
    new student() { Id = 2, Name = "Swathi" },
    new student() { Id = 3, Name = "Sudhan" }
};
var numbers = (from x in list
                        where x.id > 1
                        select x).ToList();

Students.Add(new Student() { Id = 4, Name = Vellingiri };

foreach(Student s in numbers)       
Console.Writeline(s.Name);
//Doesnt reflect the newly added student since the query gets executed immediately

Output:
Swathi
Sudhan

Comments