Sunday, August 16, 2015

Difference between Deferred Execution and Immediate Execution in c#?


Deferred Execution

LINQ query has three operations to execute:
  1. Get the data source
  2. Create the LINQ query
  3. Execute the query

Example:
        static void Main()
        {
            List<int> Number = new List<int> { 500, 400, 800, 620, 720};
            IEnumerable<int> desNumber = from i in Number
                                               orderby i
                                               select i;

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

            Console.ReadLine();
        }

Result:
400
500
620
720
800

The above LINQ query execution is called deferred execution.


Immediate Execution

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

Example:
        static void Main()
        {
List<int> Number = new List<int> { 500, 400, 800, 620, 720};
            IEnumerable<int> desNumber = from i in Number
                                               orderby i
                                               select i;
            //Immediate Execution
            int maxNumber = desNumber.Max();
            Console.WriteLine(maxNumber);

            Console.ReadLine();
        }

Result:

800

No comments:

Post a Comment