Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool



Linq and Delayed execution

If you have not taken a look at Linq (either Linq to objects or Linq to sql) you need to do so.  I would say it is the coolest new feature that was released with .Net 3.5.  But there is one thing that you MUST keep in mind when using Linq.  It has been designed to perform lookups using delayed execution.  When you declare your Linq statement all you are doing is creating the memory representation of the query as an express tree.  The execution of this plan will NOT be executed until the first time you attempt to access the result set of the Linq query.

But before we get started I want to show the demo object model I will be using for this post.

public class Demo
{

    public string Name { get; set;  }
    public string Text { get; set; }
    public Int32 Count { get; set;  }

    public static List BuildDemoList()
    {
        return new List< Demo >
                   {
                       new Demo {Name = "First", Text = "Some", Count = 123},
                       new Demo {Name = "Second", Text = "Other", Count = 223},
                       new Demo {Name = "Third", Text = "Value", Count = 443},
                       new Demo {Name = "Fourth", Text = "Goes", Count = 224},
                       new Demo {Name = "Last", Text = "Here", Count = 5534}
                   };
    }
}

Lets take a look at a few examples to help demonstrate how Linq's delayed execution works

This first block simply shows how you can query a collection and spit out the contents

List< Demo > values = Demo.BuildDemoList();
var result = from d in values
             where d.Count >= 224
             select d;

foreach ( var demo in result )
{
    System.Diagnostics.Debug.WriteLine( string.Format( "{0}, {1}, {2}", demo.Name, demo.Text, demo.Count ) );
}

// output
// Third, Value, 443
// Fourth, Goes, 224
// Last, Here, 5534

This second block does the same as the ones above, but with a twist.  Because we are changing the value of an item in the list PRIOR to using it we are going to change the results.

List values = Demo.BuildDemoList();
var result = from d in values
             where d.Count >= 224
             select d;

values[ 2 ].Count = 100;

foreach (var demo in result)
{
    System.Diagnostics.Debug.WriteLine(string.Format("{0}, {1}, {2}", demo.Name, demo.Text, demo.Count));
}

// Output
// Fourth, Goes, 224
// Last, Here, 5534

This final block appears to be the exact same as the second above, but with one small change.  We have called the .ToList() on the Linq statement.  By calling the .ToList() we are forcing the execution of the query immediately. Now when we change a value in the underlying collection and then iterate over the results we will NOT get the changes.

List values = Demo.BuildDemoList();
var result = ( from d in values
             where d.Count >= 224
             select d ).ToList();

values[2].Count = 100;

foreach (var demo in result)
{
    System.Diagnostics.Debug.WriteLine(string.Format("{0}, {1}, {2}", demo.Name, demo.Text, demo.Count));
}

// Output
// Third, Value, 100
// Fourth, Goes, 224
// Last, Here, 5534

The thing I would like to stress here is that Linq by default will NOT execute the query prior to the first use.  I know this will cause issues for some, and may be very hard to spot if you do not understand this fact.

Till next time,



Comments

Reflective Perspective - Chris Alcock » The Morning Brew #68 said:

Pingback from  Reflective Perspective - Chris Alcock  &raquo; The Morning Brew #68

# April 8, 2008 3:10 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Derik Whittaker

Derik is a .Net Developer/Architect specializing in WinForms working out the northern suburbs of Chicago. He is also believer and advocate for Agile development including SCRUM, TDD, CI, etc.

When Derik is not writing code he can be found spending time with his wife and young son, climbing on his bouldering wall, watching sports (mostly baseball), and generally vegging out. Check out Devlicio.us!

Our Sponsors

Proudly Partnered With


This Blog

Syndication

News