在路上

导航

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.

posted on 2013-05-22 21:10  Clarence Yang  阅读(683)  评论(2编辑  收藏  举报