Foreach 更改未保留在 Linq 项目集合上
在下面的示例中,当我返回集合时,不会保留在 foreach 中应用的更改:
var people = SomeLinqToSqlSource();
foreach (var person in people)
{
person.Name = "Jimmy";
}
return people.AsQueryable();
这与我的理解相矛盾,即在 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();
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?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是
people
是一个IQueryable
,当您返回它并且消费者枚举结果时会重新查询 - 您更新的属性现在已经消失了,因为每个person
实例是通过执行查询来重建的。如果您想保留更改,则必须首先具体化数据,即使用
ToList()
,然后将列表作为IEnumerable
(或IList
>)The problem is that
people
is anIQueryable
and is re-queried when you return it and the consumer enumerates the results - your updated properties are gone now, since eachperson
instance is reconstructed by executing the query.If you want to preserve changes you have to materialize your data first, i.e. using
ToList()
and then return the list as anIEnumerable
(orIList
)