.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Imran Ghani
Sohaib Khalid

Home >> Articles >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Lazy Execution or Internal of Deferred in LINQ

Posted By:Dhananjay Kumar       Posted Date: January 30, 2011    Points: 75    Category: LINQ    URL: http://www.dotnetspark.com  

In this article we will see how internally Deferred or lazy execution is implemented.

Internal of Deferred or Lazy Execution in LINQ

I have already posted about Deferred Execution here

In this post we will see how internally Deferred or lazy execution is implemented.

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

Here the result variable does not contain the actual result. To get the result, we may iterate through the result (query) variable in loop as many time as we want.  We do defer execution mainly when multiple values is being returned from the query.

Deferred execution can be avoided

  1. By returning single item from the query

  2. By converting the query in  .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 Where(this IEnumerable source,
                                              Func 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 cached for better optimization.  So here execution is delayed until final query is ready to execute

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend