LINQ and Collections

When we first upgraded to the .NET 3.5 framework, the one feature I wasn’t the biggest fan of was LINQ. My main reason for the dislike is the way the syntax stands out from everything else around it. It reminded me of when I was a COBOL developer, and the code would have inline DB2 or IMS logic, which stood out from everything else. It may be powerful, but it just doesn’t look or feel right.

Well, over time I got over it. We have used LINQ a lot in this Silverlight project I am working on. The main use is for getting a distinct list of items, or to quickly filter or sort. It works great for this. The other day I found an even greater use.

Let’s say you have an object that looks like this:

public class TitleRight
{
    public Guid ID { get; set; }

    public List<Territory> Territories { get; set; }

    public List<Language> Languages { get; set; }
}

Now, let’s say you have a list of TitleRight objects, and you want to find the ones in the list that have a certain TerritoryID and a certain LanguageID. In the past, one way you would accomplish this would be to iterate through the list of TitleRights, and for each one, you would then iterate through the list of Territory and Language, and try to match on the ID.

Now, in .NET 3.5, with the help of LINQ and Lambda expressions, you can do the following

var query = from tr in TitleRights
            where tr.Territories.Find(t => t.Id == territoryId) != null &&
                  tr.Languages.Find(l => l.Id == languageId) != null
            select tr;

So, what is this code doing? It uses the List<T>.Find() method to search the list for a match, returning NULL if nothing is found. It took a little trial and error for us to figure this out, but in the end I think it truly shows the power of LINQ. This accomplished in 4 lines of code, something that would normally take probably 2 - 3 times as many.
|