为什么没有在一个IEnumerable变化到现场执行的? [英] Why isn't the change to a field in an IEnumerable executed?

查看:138
本文介绍了为什么没有在一个IEnumerable变化到现场执行的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是发现下面的调用似乎没有记住该领域所做的更改一个惊喜。

 私人无效美孚(IEnumerable的< Blopp> blopps)
{
的foreach(在blopps Blopp blopp)
blopp.SomeField = PREFIX + blopp.SomeField;

字符串测试= blopps.First()SomeField。
}



测试的变量没有前缀当数组使用LINQ to数据得到。我需要评估的的IEnumerable 的,并使其成为列表的,以使更改领域维持。为什么会这样呢?我希望该计划认识到该领域的以后使用,并对其进行评估。

 私人无效美孚(IEnumerable的< Blopp> _blopps)
{
名单,LT; Blopp> blopps = _blopps.ToList();
的foreach(在blopps Blopp blopp)
blopp.SomeField = PREFIX + blopp.SomeField;

字符串测试= blopps.First()SomeField。
}


解决方案

这要看你传递什么进去。如果它是一个的懒洋洋地评估顺序的,则每次你看 blopps ,将重新评估的投入。



如果你像一个列表与下传; T> ,序列将包含每次完全相同的值,这样很好。如果在unmaterialized查询传递,则在每次你看看输入时间执行查询。是否返回到相同的对象的引用作为先前的评估将取决于究竟它在做什么。



(如在评论中所指出,在一些情况下,改变的对象返回的由一个评价甚至可以改变完全查询的结果 - 的对象可以以这样的方式,它们然后不早于该查询相匹配的过滤器被修改)


This was a surprise to discover that the following call didn't seem to remember the changes made to the field.

private void Foo(IEnumerable<Blopp> blopps)
{
  foreach (Blopp blopp in blopps)
    blopp.SomeField = PREFIX + blopp.SomeField;

  String test = blopps.First().SomeField;
}

The test variable lacks the prefix when the array is obtained using LINQ to data. I need to evaluate the IEnumerable and make it a List in order to make the changes to the fields sustain. Why is it so? I would expect the program to recognize that the field is used later on and evaluate it.

private void Foo(IEnumerable<Blopp> _blopps)
{
  List<Blopp> blopps = _blopps.ToList();
  foreach (Blopp blopp in blopps)
    blopp.SomeField = PREFIX + blopp.SomeField;

  String test = blopps.First().SomeField;
}

解决方案

It depends on what you pass into it. If it's a lazily evaluated sequence, then each time you "look" at blopps, it will re-evaluate the input.

If you pass in something like a List<T>, the sequence will contain the same exact values each time, so that's fine. If you pass in an unmaterialized query, it will execute the query each time you look at the input. Whether that returns references to the same objects as the previous evaluation will depend on exactly what it's doing.

(As noted in comments, in some cases, changes to the objects returned by one evaluation could even change the results of the query completely - the objects could be modified in such a way that they then don't match filters earlier in the query.)

这篇关于为什么没有在一个IEnumerable变化到现场执行的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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