Deferred Execution in LINQ

Wanna see something neat?  Create an ASPX page in Visual Studio and add a GridView Control. Leave the name as GridView1.

(You can do this any number of ways, but I happened to do it in an aspx page.)

In your codebehind page, add the following to the form.Load event:

Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
    Dim filter As String = "System"
    Dim query = From a In AppDomain.CurrentDomain.GetAssemblies() _
                Where a.GetName().Name.Contains(filter) _
                Select a.GetName.Name

    'filter = "Xml"

    GridView1.DataSource = query
    GridView1.DataBind()
End Sub

Now run the page. You should see something that looks like this:

image

You should be looking at a list of Namespaces that begin with "System."  Once you're done ooh'ing and ahh'ing over it, go back to your codebehind page and uncomment the 'filter = "Xml" line.

Now you're probably thinking, so what Chris, it's not going to do anything because it's AFTER the query...  But that is where you'd be wrong. See there's this thing called Deferred Execution, and it's part of LINQ. It gives us a lot of flexibility. Trust me on this.

So, if you uncomment that line, and run the code again, this time you should see something like this:

image

I know, crazy huh?

What happens is this... when you create your query, it's not actually executing until you need it. In this case, it's the databind. In other cases, it might be when you call the .ToArray method of your resultset, or when you add the contents to a custom object.

Enjoy.

This article is part of the GWB Archives. Original Author: Chris G. Williams

New on Geeks with Blogs