的foreach变化没有被保存LINQ的项目集合 [英] Foreach changes not being preserved on Linq item collection

查看:145
本文介绍了的foreach变化没有被保存LINQ的项目集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的例子中,在foreach应用的更改,当我返回集合将不会保留:

In the following example, changes applied in the foreach are not preserved when I return the collection:

var people = SomeLinqToSqlSource();

foreach (var person in people)
{
   person.Name = "Jimmy";
}

return people.AsQueryable();

这违背我的理解是一个foreach(..)内,您可以通过引用在当前操作项目。

This contradicts my understanding that within a foreach(..), you operate by-reference on the current item.

有谁请让我知道我要去哪里错了?

Could anybody please let me know where I'm going wrong?

感谢。

推荐答案

的问题是, IQueryable的并重新查询,当您返回它和消费者列举的结果 - 现在你更新的属性都消失了,因为每个实例是通过执行重建查询。

The problem is that people is an IQueryable and is re-queried when you return it and the consumer enumerates the results - your updated properties are gone now, since each person instance is reconstructed by executing the query.

如果您想保留你必须先兑现你的数据,即采用了ToList()修改然后返回列表作为的IEnumerable (或的IList

If you want to preserve changes you have to materialize your data first, i.e. using ToList() and then return the list as an IEnumerable (or IList)

这篇关于的foreach变化没有被保存LINQ的项目集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆