When should I convert a loop over collection to Linq statement?

c#, linq, loops, resharper

Solution

Does this improve performance?

In general it does not affect performance. It is possible to engineer situations where using LINQ either improves or degrades performance, but not in the general case.

Does this make code more readable?

A lot of times yes, because it replaces a construct that emphasizes the mechanics of the iteration with one that emphasizes the purpose of the iteration.

Emphasis on mechanics:

var jacks = new List<Person>();
foreach (var person in persons)
{
    if (person.Name == "Jack")
    {
        jacks.Add(person);
    }
}

"This code iterates over persons, and every time it finds a person named Jack it adds them to the list named jacks".

Emphasis on purpose:

var jacks = persons.Where(p => p.Name == "Jack").ToList();

"Take all persons whose name is Jack and put them into a list. We 'll call that list jacks."

It also doesn't hurt that the second version is much shorter, so your brain can consume it all at once much more readily than the first.

Another example:

var furryAnimals = furryThings.Intersect(animals).ToArray();

There is absolutely no way you are going to be able to match the clarity of this without LINQ or writing your own equivalent. Here it is immediately clear that `furryAnimals` contains anything that is both in `furryThings` and in `animals`. That's all you care about.

You don't care about exactly how the intersection of these sets is calculated. The calculation might involve a dictionary as an implementation detail. But an alternative version of the code that starts with creating that dictionary immediately draws your attention to the one thing that is least important: the implementation detail.

In general, when should I follow ReSharper suggestion in this matter, and when I should not?

There are always exceptions to the rule, so I won't try to present one here. But in general we want code to be correct, maintainable and fast (usually in that order). I am going to assume that the code is correct either way, so whenever you have to make a decision, always consider:

- does the change make the code clearer to understand? does it make the code easier to modify in the future?

If you have concrete proof that the speed of the code is critical, also consider:

- which version runs faster?

Problem

I recently starter using ReSharper. ReSharper suggests to convert all your loops over collections (usually `foreach`) to a `Linq` statement, even if the loop contains various conditioning. - Does this improve performance? - Does this make code more readable? In general, when should I follow ReSharper suggestion in this matter, and when I should not?

Original source