Thinking outside the box

SteelePrice.Net

My Links

Twitter Updates


Get Microsoft Silverlight
follow me

Article Categories

Archives

Post Categories

Image Galleries

Dot Net

General

Linux

OneNote

Windows

TechED Bloggers
Visual Basic Bloggers (OPML)

Thinking Different with Linq and Lambdas

Today I had to look through a set of controls to extract the Text and build a dynamic search.

Normally, this means looping and/or a bunch of Ifs to do some validation.  With Linq to Objects at our disposal I distilled exactly what I needed down to this:

 

Dim q = From c In SearchCriteria.Controls _
        Where TypeOf c Is RadTextBox _
        AndAlso c.Text.Length > 0

Dim params = q.ToDictionary(Of String, String)( _
                Function(r As RadTextBox) r.ID.Remove(0, 5), _
                Function(r As RadTextBox) r.Text.Trim)

At first glance this is a so what... until you look at what it is really doing for me.

I am looking at a Web Page that I need to extract a bunch of criteria from and many of them will most likely be blank, so why even loop through them?  The AndAlso takes care of any problems arising from controls that are not RadTextBox.  Additionally, I need to take the results and put them into a Dictionary so that I can pass this onto my Dynamic Query routine.

The code this is replacing is about 30 lines of code (that I didn't write...) and I can see exactly what is going on in this concise format.  All I had to do is think a little different from the old habits of coding and apply some of the great new tools we have at our disposal.  What the Old code did was to loop through all the controls in the SearchCriteria DIV and check to see if .Text was filled, but to do that, it needed to cast the Control.  Then on top of that it needed to add the Dictionary Item.

This new code could actually be written on one line, but for programming clarity and readability, I broke it up.

Now this really reads easy and works perfectly, thanks to Linq.  A little refactoring and this could become a permanent addition to a Utilities class.

nb: the Remove leverages the fact that I use "Find_<DBFieldName>" in markup and not have to resort to bindings or strings, it also makes this a candidate for a code generation template.

posted on Tuesday, June 03, 2008 5:06 PM

Feedback

# Interesting Finds: June 4, 2008 6/4/2008 7:22 AM Jason Haley      

Post a new comment about this topic
Title  
Name  
Url

Comments   
Enter the code you see:
   

Blogroll Me!

Copyright © 2003-2009 H. Steele Price, IV -
All opinions are my own, not necessarily those of my employer, your mother, or any government agency.