When should we use LINQ?

Microsoft LINQ integrates queries directly into .NET languages, making it easy to work with collections. The best part about LINQ is that it allows us to say what we want to do to a set, without telling it how. This decreases code complexity, without losing any functionality.

For example, say we had the following function:

IEnumerable GetAboveTwo(int[] numbers)
{
    var aboveTwo = new List<int>();

    foreach(int n in numbers)
        if (n > 2)
            aboveTwo.Add(n);

    return aboveTwo;
}

We could read this roughly as, “Create a temporary collection.  For each number, if it is greater than two, add it to a collection to be returned.  Finally, return the temporary collection.” This isn’t a bad method, but it could be better. Using LINQ, we can rewrite it as:

IEnumerableGetAboveTwo(int[] numbers)
{
    return from n in numbers
           where n > 2
           select n;
}

Now, we have “return every number greater than two.” Note that it states what will be returned, not how. In the net post, we’ll actually measure the maintainability of each approach.

What sort of performance cost do we pay for the luxury of LINQ?  When performance matters more than maintainability, we must develop tests to determine the best solution. In the upcoming posts, we’ll learn how to quantify LINQ’s impact on both performance and maintainability.

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.Donald Knuth

Tags: ,