Child pages
  • Possible multiple enumeration of IEnumerable

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Redirect
locationhttp://www.jetbrains.com/resharperplatform/help?Keyword=PossibleMultipleEnumeration

Consider the following code snippet:

Code Block
none
none

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 + " ");

...

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.:

Code Block
none
none

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

...