没有被保存查询的更改到一个IEnumerableIEnumerable

2023-09-05 02:02:54 作者:为XX打call.

的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.