Sunday, January 6, 2013

Deferred Execution and Immediate Execution in c#?


Deferred Execution and Immediate Execution

To understand the Deferred Execution and Immediate Execution, first we have a look on “How LINQ query execute”.
A LINQ query has three operations to execute:

  • Get the data source
  • Create the LINQ query
  • Execute the query


Example

        static void Main()
        {
            // Employee Salary data source
            List empSalary = new List { 3500, 2400, 8500, 6800, 7500, 9500, 2800, 6500, 4500, 7000 };

            // LINQ query
            IEnumerable decendingSalary = from i in empSalary 
                                               orderby i
                                               select i;

            //Execute Query (Deferred Execution)
            foreach (int salary in decendingSalary)
            {
                Console.WriteLine(salary);
            }

            Console.ReadLine();
        }

Result

2400
2800
3500
4500
6500
6800
7000
7500
8500
9500

The above LINQ query execution is called deferred execution.

Sometime you need query result count, min number and max number etc. to get the number count or min max number you have to use Count, MIN and MAX method. This execution is called immediate execution.

        static void Main()
        {
            // Employee Salary data source
            List empSalary = new List { 3500, 2400, 8500, 6800, 7500, 9500, 2800, 6500, 4500, 7000 };

            // LINQ query
            var decendingSalary = from i in empSalary 
                                               orderby i
                                               select i;
            //Immediate Execution
            int maxNumber = decendingSalary.Max();
            Console.WriteLine(maxNumber);

            Console.ReadLine();
        }

Result

9500


No comments:

Post a Comment