Posts Linq - Episode 1

Linq - Episode 1

Linq is very, very, very cool.  I can easily envision looking three years from now and wonder "how did we write software without Linq?".  Several recent language editions have helped to reduce code needed and thus made my development life easier.  However, I have to say that Linq is something that seems to hit a home run in several distinct areas to improve my development life.  Over the next few posts, I'm going to outline a few "real world" examples that I've been using.  Understand, I'm still learning Linq... and even without knowing all of the ins and outs, it is extremely helpful in everyday coding.

Finding, filtering, connecting data is much more "natural" using Linq.  No more using a For loop to find a piece of information.  How many times have you written the following code:

Dim exists As Boolean
For Each item As SomeClass In items
  If item.SomeValue = targetItemValue Then
    exists = true
    Exit For
  End If

All of this just to find out if we have a value that matches.  Now compare that with the following:

Dim exists = (From item In items _
                   Where item.SomeValue = targetItemValue _
                   Select item).Count > 0

Sure, it's less "code"; however, the real point here is that once you have a basic understanding (and I do mean basic) of Linq, the above code is much more concise and very quickly expresses the overall intent.  I firmly believe that coming back after a year and seeing the above two versions of code, the Linq one will be much more easily to grok and maintain.

Unfortunately there is a downside to Linq.  Linq doesn't seem to play nice with Edit & Continue; so if you have issues with your Linq statement(s), you won't be able to change them while debugging.  This is extremely unfortunate as I see it will hinder some of the adoption rate for integrating Linq into existing projects.  However, under real world scenarios, I've been able to, using Linq (even without E&C) to restructure complicated code, make it much more understandable, improve on the overall logic because it's more understandable and create (hopefully) much more robust code in the long run.  The lack of E&C is a let down, but overall I think the down side is acceptable given what is gained.

See you in the next installment.

This post is licensed under CC BY 4.0 by the author.