I <3 LINQ

Posted on February 5th, 2008 by Tim.
Categories: General/Misc..

I just started a little pet project, and figured this would be a good time to start training myself to think in terms of LINQ. I started out writing a function that looked sort of like this:

public double Length
{
  get
  {
    double max = 0;
    foreach (FunctionClip clip in _clips)
    {
      max = Math.Max(max, clip.End);
    }
    return max;
  }
}

Then I noticed that there was an extension method called Max on arrays. As a result, the above function simplifies to:

public double Length
{
  get
  {
    return _clips.Max(f => f.End);
  }
}

Six lines of code suddenly turned into one! At this point, the gears were turning in my head. Suddenly, the foreach construct seemed less elegant:

foreach (FunctionClip clip in _clips)
{
  clip.RenderTo(data, freq);
}

Could this be made simpler? Sure, check it out:

_clips.ForEach(c => c.RenderTo(data, freq));

Not quite as dramatic as before, but in raw number of lines we’ve still reduced by a factor of four. Making code more compact increases readability, which in turn leads to less bugs. LINQ FTW!

6 comments.

Chris

Comment on February 5th, 2008.

That reminded me of this:

http://www.stanford.edu/class/cs242/readings/backus.pdf
Section 5

Chris

Comment on February 10th, 2008.

I was reading about LINQ the other day, and I was under the impression that the second statement would look more like:

From c in _clips select c.RenderTo(data, freq);

though that method would have to discard its output.

Tim

Comment on February 11th, 2008.

That would make sense if you wanted an array with the results of that function… technically my example wasn’t truly LINQ, since I wasn’t doing any querying, but using lambda expressions and extension methods are closely related features.

Chris

Comment on February 18th, 2008.

Isn’t there a name for those features though, besides LINQ?

Tim

Comment on February 18th, 2008.

C# 3.0?

Chris

Comment on March 9th, 2008.

Yar. I think we’ve agreed that ain’t LINQ up there. Now it needs a picture.

Leave a comment

Comments can contain some xhtml. Names and emails are required (emails aren't displayed), url's are optional.