ReSharper
 
Get ReSharper
Get your hands on the new features ahead of the release by joining the Early Access Program for ReSharper 2025.1! Learn more

Code inspection: Possible multiple enumeration

Last modified: 11 February 2024

Consider the following code snippet:

Assuming that GetNames() returns an IEnumerable<string>, we are, effectively, doing extra work by enumerating this collection twice in the two foreach statements.

It could get even worse if GetNames() results in a database query, in which case you could end up getting different values in both foreach loops if some other process changes the database between the two calls.

This kind of problem can be easily fixed — force the enumeration at the point of variable initialization by converting the sequence to an array or a list, for example:

The rest of your code can stay the same, because both array and list types implement the IEnumerable interface.