Deferred vs Immediate execution in Linq

Posted by Jalpesh P. Vadgama on ASP.net Weblogs See other posts from ASP.net Weblogs or by Jalpesh P. Vadgama
Published on Wed, 26 Jun 2013 21:09:21 GMT Indexed on 2013/06/26 22:22 UTC
Read the original article Hit count: 530

Filed under:
|
|
|

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

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about c#