zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    PHP添加Redis模块及连接
    Redis高级应用
    Redis常用命令
    Redis的数据类型及操作
    Redis下载及安装部署
    NoSQL介绍
    8种Nosql数据库系统对比
    JQ插件
    libcurl一般用法
    密钥对加密原理
  • 原文地址:https://www.cnblogs.com/iwilltry/p/3093643.html
Copyright © 2011-2022 走看看