One of the first things every programmer learns in how to loop through an array of information. We learn how to do for, foreach, while loops but then we never really improve on them. For the most part the standard loop is as far as a programmer goes.

It seems to me that loops should be more intelligent than that. In fact we often write code that uses the loop for additional information. It isn't uncommon to see a loop check if it is an even or odd index or the first or last value.

Modestly Smarter Loops

I really like lambdas a lot - in fact probably, too much. Being able to pass an delegate around like an argument definitely can be abused but in some cases it can make for some really elegant code. Let's look at some code that can improve working with arrays.

Now that is a lot of code but if you review over it you'll find that it is a set of extension methods that can be used with IEnumerable. The basic idea is that we can perform our loop within a delegate that accepts additional information about the elements in our loop.

Normally you would simply write all the comparisons within your loop and then use them as needed. Instead, in this code, we pass in an additional parameter that contains shortcuts to many common comparisons you might find inside of loops. By doing this we improve readability and focus on what the loop is doing.

Whats Wrong With The Old Way

Nothing! Writing your comparisons inline can be advantageous since you aren't doing any more work than you need to do. However, in some cases, the improved readability would make a big difference in the quality of the code. Consider the two snippets of MVC code and decide with one is easier to read.

This example shows using only the ElementDetail class but of course you could use the other extension method that also supplies the value by itself.

Everyone has heard the advice before "Write Code For Humans Not For Computers" - more or less, readability is probably the most important part of your code. The computer can read both of those examples easily whereas a human might need to think for a moment before they are positive what the code does.

In any case, this simple but effective approach can transform previously unreadable code into works of programming art... or something like that...