Thursday, November 20, 2008

LINQ - Just because you can

Day after day, the .NET Framework evolves in a fantastic way and if you know how to take advantage of the new features, your productivity can actually improve. However, if you don’t have the knowledge, you will do rude mistakes. The latest I encountered was something like this (adapted to the widely used person example and reduced to fit the blogpost):

(click to enlarge)

The idea was to search a collection (in this case, a Person’s collection) and print out the items that did match a certain condition (in the above example, Person’s whose age is over 18). So far so good, the output is what was expected. But the programmer decided that would be “cool” to write it using LINQ. Can you identify the problem on the above example?

Well, as you might expect, the “Where” extension doesn’t actually perform as “an SQL where clause”. The “Where” extension translates in a foreach statement:

(click to enlarge)

So, in the above example, first the user iterates through the collection to find the items that match the condition and then iterates through those items to print them. Two foreach statements, something that could be done with one foreach and one if clause… And that’s not all, but it’s enough to make my point of view.

I know this is a “way too basic” example, but the point is that tools shouldn’t be used “just because you can” or “they’re cool”. LINQ is useful in a wide number of scenarios but not on every task you have.