Deferred Execution in LINQ

Deferred Execution of Query

  class Sample
    {
      public int i;
      public String str;
    }

  static void Main(string[] args)
    {
      List lst = new List();
      lst.Add(new Sample() { i = 1, str = "String1" });
      lst.Add(new Sample() { i = 2, str = "String2" });
      lst.Add(new Sample() { i = 3, str = "String3" });
      lst.Add(new Sample() { i = 4, str = "String4" });
      int a = 1;
      IEnumerable lStr = (from l in lst
                          where l.i == a
                          select l);  //It will just store query in lStr variable.
     }

When we write any LINQ query as mentioned, it doesn't get executed immediately. It actually stores  query in the variable and every time we use/enumerate the variable it executes the query and use the result. It is called deferred execution.

    Sample s = lStr.First();  ///Query will be executed here
    Console.WriteLine(s.str);

So that whenever filter variable(a) changes prior to the use of object(lStr), output will automatically changes.

 
    IEnumerable lStr = (from l in lst
                        where l.i == a
                        select l);
    Sample s = lStr.First(); //will execute query.
    Console.WriteLine(s.str); //Output: String1
    a = 2; 
    s = lStr.First(); //will execute the query again
    Console.WriteLine(s.str); //Output: String2.