SIGN UP MEMBER LOGIN:    
ARTICLE

Internals of Deferred or Lazy Execution in LINQ

Posted by Dhananjay Kumar Articles | LINQ with C# February 01, 2011
In this article we will see the internals of Deferred or Lazy Execution of LINQ
Reader Level:


I have already posted about Deferred Execution here

In this article we will see the internals of Deferred or Lazy Execution of LINQ.

Deferred Execution executes the query only when a loop starts. What I mean here is that, we iterate through the query variable to get the result.

  linq.gif

Here the result variable does not contain the actual result. To get the result, we may iterate through the result (query) variable in a loop as many times as we want. We do deferred execution mainly when multiple values are being returned from the query.
 
Deferred execution can be avoided

  1. By returning single item from the query
  2. By converting the query using ToList().

Lazy evolution of deferred execution is executed using the yield operator in C# 3.0

In C# 3.0 it is implemented as below.

public static class Sequence
    {
        public static IEnumerable<T> Where<T>(this IEnumerable<T> source,
                                              Func<T, bool> predicate)
        {
            foreach (T element in source)
                if (predicate(element))
                    yield return element;
        }
    }


The main advantage of lazy evolution is if query is returning large result it will be cached for better optimization. So here execution is delayed until final query is ready to execute.

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Nevron Gauge for SharePoint
Become a Sponsor