Deferred vs Immediate execution in Linq

In this post, We are going to learn about Deferred vs Immediate execution in Linq.  There an interesting variations how Linq operators executes and in this post we are going to learn both Deferred execution and immediate execution.

What is Deferred Execution?

In the Deferred execution query will be executed and evaluated at the time of query variables usage. Let’s take an example to understand Deferred Execution better.

Example:

Following is a code for that.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var customers = new List<Customer>(
                new[]
                    {
                        new Customer{FirstName = "Jalpesh",LastName = "Vadgama"},
                        new Customer{FirstName = "Vishal",LastName = "Vadgama"},
                        new Customer{FirstName = "Tushar",LastName = "Maru"}
                    }
                );

            var newCustomers = customers.Where(c => c.LastName == "Vadgama");

            customers.Add(new Customer {FirstName = "Teerth", LastName = "Vadgama"});

            foreach (var c in newCustomers)
            {
                Console.WriteLine(c.FirstName);
            }
        }

        public class Customer
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }

    }
}

More on my personal blog @www.dotnetjalps.com

Shout it
Published Thursday, June 27, 2013 3:39 AM by Jalpesh P. Vadgama
Filed under: , , ,

Comments

No Comments