Menu

Reduce redundancy with LINQ

September 4, 2012 - Programming

LINQ, or Language Integrated Query, is one of the most powerful constructs available in C#. For the most part, it doesn’t actually do anything you cannot do otherwise, but it removes a lot of otherwise standard boilerplate code when dealing with Enumerations, filtering them, etcetera.

Once you start “getting into” LINQ, you find it useful everywhere. For example, take this sort of typical expression:

[code]
if(founddata.cFileName!=”.” && founddata.cFileName!=”..”)
[/code]

This is a rather frequent sort of expression; testing a single property or variable against a group. LINQ can reduce this nicely:

[code]
if(!new String[]{“.”,”..”}.Contains(founddata.cFileName))
[/code]

“But that doesn’t reduce it at all!” you say. “It’s exactly the same number of characters long, in fact!” And that is correct. But imagine when you have to add more tests. in the former, you need more expressions pasted on with &&; with the latter, you merely change the declaration of the array, and the Contains() extension method handles it. This is a basic example, of course.

This was simply a quick post I had an idea for. When working in a given language, always try to think of ways you could use language features to make that code more concise and easier to read. LINQ is of course no exception.

Have something to say about this post? Comment!