【发布时间】:2019-01-31 13:43:26
【问题描述】:
谁能解释这种行为?
此代码有效:
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*/
select 函数似乎返回一个新的IEnumerable,在fullPathTabAssociation.Clear() 之前进行调试,在这两种情况下,newValues 的值都是正确的,并且与fullPathTabAssociation 不同。特别是我不明白最后一种情况会发生什么
【问题讨论】:
-
Linq 是 lazy 它只在 materialization (
.ToList()) 上工作。 -
A(延迟执行)LINQ 查询只是一个查询。它描述了检索您想要的内容必须执行的操作。它尚未执行。如果您附加
ToList,则您实现此查询并将结果填充到列表中。您的查询的来源是字典,如果您清除它,查询将不会返回任何内容。如果先将结果填充到列表中,则由于列表未与字典耦合,因此清除字典不会清除此结果。 -
谢谢,我一直在寻找延迟行为
标签: c# linq pointers function-pointers