c# - Linq:选择有和没有 ToList()
问题描述
谁能解释这种行为?
此代码工作:
Dictionary<string, int> fullPathTabAssociation = new Dictionary<string, int>();
//bla bla..
//here fullPathTabAssociation is populated
////bla bla..
var newValues = fullPathTabAssociation
.Where(x => x.Value > index)
.Select(x => new KeyValuePair<string, int>(x.Key, x.Value - 1))
.ToList();
fullPathTabAssociation.Clear();
/*now newValues is populated with correct values*/
此代码不起作用
Dictionary<string, int> fullPathTabAssociation = new Dictionary<string, int>();
//bla bla..
//here fullPathTabAssociation is populated
////bla bla..
var newValues = fullPathTabAssociation
.Where(x => x.Value > index)
.Select(x => new KeyValuePair<string, int>(x.Key, x.Value - 1))
fullPathTabAssociation.Clear();
/*now newValues is empty*/
选择函数似乎返回一个新IEnumerable
的,在这两种情况下,在调试之前fullPathTabAssociation.Clear()
,值都是正确的newValues
并且不同于fullPathTabAssociation
. 特别是我不明白最后一种情况会发生什么
解决方案
Linq 是懒惰的;它尽可能地推迟它的工作(直到foreach
或某种具体化)。
在第一个摘录中,您在.ToList()
此处实现查询,Linq 必须执行并提供List<T>
集合:
var newValues = fullPathTabAssociation
.Where(x => x.Value > index)
.Select(x => new KeyValuePair<string, int>(x.Key, x.Value - 1))
.ToList(); // <- Materizataion an actual List<T> required; Linq executes
// Since we have newValues collection (not query) it doesn't depend on аullPathTabAssociation
fullPathTabAssociation.Clear();
在第二个摘录中,Linq不需要做任何事情:
// Just a query, no materialization
var newValues = fullPathTabAssociation
.Where(x => x.Value > index)
.Select(x => new KeyValuePair<string, int>(x.Key, x.Value - 1));
fullPathTabAssociation.Clear();
...
// Only here (on foreach or materialization) Linq has to execute the query;
// and it takes fullPathTabAssociation (which is empty)
foreach (var item in newValues) {
...
}
推荐阅读
- python - OpenCV:使用 findContours 仅获取二进制图像中的黑色轮廓
- swift - 如何正确更新修饰符?
- c - 配置:错误:C 编译器无法创建可执行文件 - Mac Sierra
- vue.js - V-model 和 materializecss M.FormSelect 问题
- android - Android 1dp stroke drawable不能在1dp高度视图中绘制
- c# - 将 IEnumerable 传递给视图以生成表单,然后将表单数据传递回控制器
- c++ - c++ cout + str.length 编程简介
- mysql - RavenDB Northwind 从 SQL 导入 - 为什么没有给 employee_privileges 一个集合?
- php - 如何从事件 URL 获取 TicketMaster 事件 ID?
- clang - 为 iOS 编译栏时找不到“迭代器”文件