• Possible multiple enumeration of IEnumerable


    Consider the following code snippet:

       1:   
       2:  IEnumerable<string> names = GetNames();
       3:  foreach (var name in names)
       4:    Console.WriteLine("Found " + name);
       5:  var allNames = new StringBuilder();
       6:  foreach (var name in names)
       7:    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. If GetNames() results in a database query, you end up doing that query twice, while both times getting the same 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.

  • 相关阅读:
    《JFlow: Practical Mostly-Static Information Flow Control》
    《嵌入式Linux C编程》第一章笔记
    Ansible --- 通过Ansible管理地区机房中的内网机器
    等保审核 --- MySQL密码复杂度
    等保审核 --- MySQL连接控制插件
    等保审核 --- MySQL操作审计记录
    CSS中居中的完全指南(中英对照翻译)
    svn提交报database is locked
    PHP session_cache_expire 会话函数
    MySQL CONCAT_WS 函数
  • 原文地址:https://www.cnblogs.com/zhanghaiyu/p/3223461.html
Copyright © 2020-2023  润新知