加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么在使用foreach时LINQ查询不执行?

发布时间:2020-12-15 03:43:49 所属栏目:百科 来源:网络整理
导读:在LINQ语句中创建新对象时,例如: var list = new Liststring() { "a","b","c" };var created = from i in list select new A(); A类看起来像这样: class A{ public string Label;} 然后用foreach循环修改A中的属性: foreach (var c in created) { c.Label
在LINQ语句中创建新对象时,例如:
var list = new List<string>() { "a","b","c" };
var created = from i in list select new A();

A类看起来像这样:

class A
{
    public string Label;
}

然后用foreach循环修改A中的属性:

foreach (var c in created) {
    c.Label = "Set";
}

为什么以后在IEnumerable中访问对象时没有设置值.例如.以下断言失败:

Assert.AreEqual("Set",created.ElementAt(2).Label);

我不知道为什么会发生这种情况.我期望foreach-statement执行查询,并触发对象的创建. MSDN文档规定:“Execution of the query is deferred until the query variable is iterated over in a foreach or For Each loop”.

我已经用.NET 4.5和Mono 3.2.0转载了这个行为.在访问创建的对象之前,在IEnumerable上调用ToList会使此问题消失.

解决方法

这是因为创建的是查询,而不是结果.所以,每次你列举它,你都从头开始评估选择.

如果你想要这个工作,创建一个实际的列表,而不是只是一个表示一个查询的IEnumerable.

例如,添加:

created = created.ToList();

你说:

I would expect the foreach-statement to execute the query,and trigger the creation of the objects

这正是发生了什么.问题是每次迭代创建的对象的创建,而不仅仅是第一次.由于ElementAt()方法迭代创建,它只是再次创建新的As.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读