Code Inspection: Possible multiple enumeration of IEnumerable

Last modified: 08 March 2021

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.