Possible multiple enumeration of IEnumerable
https://www.jetbrains.com/help/resharper/2016.1/PossibleMultipleEnumeration.html
Consider the following code snippet:
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 + " ");
Assuming that GetNames()
returns an IEnumerable<string>
, we are, effectively, doing extra work by enumerating this collection twice in the twoforeach
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.
问题:如果GetNames是一个sql语句操作的话,2次的foreach会导致2次的sql查询
如果转为List,那么第二次遍历的时候,直接用第一次转换是List,就不会有2次的sql查询
最新文章
- iOS UITableView 引起的崩溃问题
- ASP.NET Web API 跨域访问
- 使用MSCOMM发送任意文件,还有一些注意事项
- hbase与Hadoop
- Serializable 序列化为文件
- delphi7调用java写的webservice,在调用的时候弹出“wssecurityhandler:request does not contain required security header”
- Linux中处理需要传输的IP报文流程
- SendMail如何签名
- javaScript 比较数字大小
- Debian 8 下安装持续集成的工具Jenkins
- JAVA下JSON的类型输出及使用
- MySQL EXTRACT() 函数
- C语言之linux内核实现位数高低位互换
- VMWAR-workstatuon
- E: 无法打开锁文件 /var/lib/dpkg/lock-frontend - open (13: 权限不够)E: 无法获取 dpkg 前端锁 (/var/lib/dpkg/lock-frontend),请查看您是否正以 root 用户运行?
- day13: 迭代器和生成器
- 苹果电脑thunderbolt连接两台电脑启动方法
- 界面编程之QT窗口系统20180726
- zsh与oh-my-zsh
- shell 字符串提取数字