没有被保存查询的更改到一个IEnumerable [英] Changes to an IEnumerable are not being kept between queries

查看:135
本文介绍了没有被保存查询的更改到一个IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的IEnumerable 是懒洋洋地评估一个查询。但显然我的理解是有点瑕疵。我期望以下工作:

IEnumerable is a query that is lazily evaluated. But apparently my understanding is a bit flawed. I'd expect the following to work:

        // e.Result is JSON from a server
        JObject data = JObject.Parse(e.Result);
        JsonSerializer serializer = new JsonSerializer();

        // LINQ query to transform the JSON into Story objects
        var stories = data["nodes"].Select(
                   obj => obj["node"]).Select(
                        storyData => storyOfJson(serializer, storyData));

        // set a value on each story returned by the query
        foreach (Story story in stories)
        {
            story.Vid = vid;
        }

        // run through the query again, making sure the value was actually set
        foreach (Story story in stories)
        {
            // FAILS - story.VID is 0
            Debug.Assert(story.Vid == vid);
        }

我是什么误会?我如何可以改变的结果,这是什么查询返回?

What am I misunderstanding here? How can I alter the results of what this query returns?

推荐答案

每次枚举故事变量中,选择电话再次运行,创建一组新的故事的对象。

Each time you enumerate the stories variable, the Select call runs again, creating a new set of Story objects.

因此​​,每个的foreach 环路上一组不同的故事情况下运​​行。

Therefore, each foreach loop runs on a different set of Story instances.

您需要强制LINQ要求通过调用来评价恰好一次 .ToArray()
通过得到的数组循环不会重新评估LINQ调用(因为它是一个正常的数组),所以你共享同一组的故事实例。

You need to force the LINQ calls to evaluate exactly once by calling .ToArray().
Looping through the resulting array will not re-evaluate the LINQ calls (since it's a normal array), so you'll share the same set of Story instances.

这篇关于没有被保存查询的更改到一个IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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