Geeks With Blogs
Abhishek Anand Bits & Bytes about .net technology framework.

One of the best features of LINQ is the fact that it is lazy. Lazy or Deferred Execution allows you to specify all the conditions of your LINQ statement (Where, OrderBy, Select, etc), without actually executing those functions on the given collection until the results are needed. An example of where you can see this lazy execution in action is when using the Visual Studio Debugger. Let’s say you have an IEnumerable<int> that you want to execute a LINQ statement on and inspect the resulting values in the Debugger:

 


When you look at the values for the filtered collection, you can’t see the results immediately and you have to click the button under “Results View” to see them. The reason for this is because the LINQ expression hasn’t been evaluated yet, and clicking that button would force that evaluation.

So that is how you force the evaluation in the debugger, but what about in code? When is the LINQ statement evaluated?  To demonstrate this, we will utilize the “yield” keyword when creating our IEnumerable. For those of you unfamiliar with the yield keyword, check out this great article on Dot Net Perls.

 

        static void Main(string[] args)
        {
            var values = GetValues().Where(x => x < 5);
>>BP        Console.WriteLine(“Starting”);
            foreach (var value in values)
            {
                Console.WriteLine(value);
            }
        }
 
        static IEnumerable<int> GetValues()
        {
            for (int i = 0; i < 10; i++)
            {
>>BP            yield return i;
            }
        }

 

If we set a breakpoint on the two lines labeled “>>BP”, we can see that the values from the IEnumerable aren’t requested until after the “Starting” output. This shows that the LINQ expression on the first line deferred it’s execution until the values were needed in the foreach.

Lastly, be mindful when making calls to .ToList() and .ToArray(). These conversion functions force the execution of the IEnumerable and bring the collection into memory.

 

Posted on Monday, November 18, 2013 6:56 PM .net , linq , Deferred Execution | Back to top


Comments on this post: Deferred Execution with LINQ

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Abhishek Anand | Powered by: GeeksWithBlogs.net