ReSharper 2017.3 Help

Code Inspection: Possible multiple enumeration of IEnumerable

Consider the following code snippet:

IEnumerable<string> names = GetNames(); foreach (var name in names) Console.WriteLine("Found " + name); var allNames = new StringBuilder(); foreach (var name in names) allNames.Append(name + " ");

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 – simply force the enumeration at the point of variable initialization by converting the sequence to an array or a list, e.g.:

List<string> names = GetNames().ToList();

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

Last modified: 7 December 2017

See Also