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

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.