I don't really like
foreach loops. They are difficult to read and easy to abuse.
Let's say, for example that we want to sum up the following list of numbers:
Conventional programming wisdom says that we should do the following to find the sum of the above list:
While this code does exactly what we need, it is not very expressive in its form.
foreach loops end up looking the same whether you are trying to find the sum of a set of numbers or searching through a list of users to find a random contest winner.
Luckily for us, .NET provides a easier and more readable way to accomplish the same functionality as the
foreach loop above.
We will sum the same list of numbers using both a
foreach loop and a LINQ expression. First, let's start off with some tests so we know what we can set up our expectations early.
Now that we have our tests set up, we can move on to the actual code.
See how much easier the LINQ expression is to read? In fact, you don't even need to put anything in the parenthesis.
Taking it to the next level
The above example was a bit simple, so let's solve a problem that is a little more complex to help drive the point home. Let's say that we want to sum the squares of each item in
Just as before, we can manually find our expected answer given the same list of integers and set up our expectation before writing our production code.
Now, we can use the same methods as above which becomes more readable and succinct.