Possible multiple enumeration of IEnumerable

Consider the following code snippet:

IEnumerable<Name> names = GetNames();
foreach (var name in names)
  name.Sur="Jim";
 
foreach (var name in names)
  Console.WriteLine(name.Sur);
// won't output "Jim"

We are doing extra work by enumerating this collection twice in the two foreach statements. Since GetNames() results in a database query, you end up doing that query twice, while both times getting the same data. Once you modify the result of first query, the second query would still get the original data.

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

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

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

原文地址:https://www.cnblogs.com/iwilltry/p/3093643.html