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.

1 comment:

  1. Your Affiliate Money Printing Machine is waiting -

    And earning money online using it is as simple as 1-2-3!

    Follow the steps below to make money...

    STEP 1. Input into the system which affiliate products you intend to promote
    STEP 2. Add push button traffic (it ONLY takes 2 minutes)
    STEP 3. See how the system explode your list and sell your affiliate products on it's own!

    Do you want to start making money?

    Get the full details here

    ReplyDelete