Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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,


Posted 04-07-2008 1:11 PM by Derik Whittaker
Filed under: , ,

[Advertisement]

Comments

Reflective Perspective - Chris Alcock » The Morning Brew #68 wrote Reflective Perspective - Chris Alcock &raquo; The Morning Brew #68
on 04-08-2008 3:10 AM

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

DotNet Learner wrote re: Linq and Delayed execution
on 09-29-2009 4:16 PM

Very helpful article, thank you very much.

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)