LINQ really is hot stuff for .NET developers.

19 August 2008

8/20 7:28PM Correction: The example OrderBy code below is incorrect. Updated and explained over here.

I'm late to the LINQ party. I thought I was good at keeping up with the latest trends and improving my skills. But I never embraced the importance of using LINQ versus learning about LINQ. I'm writing to say that I finally let its concepts marinate in my head, and it's good stuff.

While making some improvements to .NET 2.0-era code, I went ahead and found some great places to use LINQ and lambda expressions to really simplify an implementation. I don't believe in blanket updating, but rather updating when it's clear, improves the maintainability, and you're looking at low-impact, low-churn changes.

I'm about 10 years behind on this one I suppose, which makes sense: I still love watching The West Wing.

Here was the previous implementation in C#:

static void SortTestClasses(List<ITestClass> classes)
{
    classes.Sort(delegate(ITestClass c1, ITestClass c2)
        {
            return Comparer<string>.Default.Compare(c1.Name, c2.Name);
        });
}

And now, with LINQ, the static method itself really is hardly useful - it's that simple:
Update: It's not really quite this simple, see here.

static void SortTestClasses(IList<ITestClass> classes)
{
    classes.OrderBy(a => a.Name);
}

Plus the addition of a Using statement for System.Linq.

This particular change was needed because I needed to update the signature of the method to take a generic IList, as opposed to a strongly typed generic List, which has a Sort method hanging off of it. But it sure does look better now.

There are a lot of good online and offline resources out there. I picked up a nice book on this last year.

At work we've been having some discussions about 3.5 language features, and although I don't always agree with every single point, I will say that here are some of the things I've been doing and following as a result of this discussion:

  • Updating private members with public properties to C# 3.0 automatic properties if you are already touching the file, and it's a minor change
  • Not using var in regular, non-LINQ code ("let's not be too lazy")
  • Trying to limit the exposure of extension methods to users of frameworks, especially to common types
  • No longer using #region's to separate properties, methods, etc. - but rather only logical components or WPF goo when it makes sense

So to the one person who hasn't figured out LINQ is cool, maybe this will help get you started.

Jeff Wilcox is a Software Engineer at Microsoft in the Open Source Programs Office (OSPO), helping Microsoft engineers use, contribute to and release open source at scale.

comments powered by Disqus