LINQ中不应推迟求和方法

问题描述:

我有以下代码:

I have the following code:

List<int> no = new List<int>() { 1, 2, 3, 4, 5 };
var res2 = no.Sum(a => a * a);
Console.WriteLine(res2);
no.Add(100);
Console.WriteLine(res2);

我希望得到以下结果:

55
10055

55
10055

但都是55

55
55

55
55

我在此处看到了有关延迟评估的信息,但没有帮助. Sum是扩展方法,但结果不是我提到的.为什么?

I have seen here which is about deferred evaluation but was not helpful. Sum is an extension method, but the result is not what I have mentioned. Why?

只有返回IEnumerable<T>的函数才可以在Linq中进行延迟(因为它们可以包装在允许延迟的对象中).

Only functions that return an IEnumerable<T> can be deferred in Linq (since they can be wrapped in an object that allows deferring).

Sum的结果是int,因此它不可能以任何有意义的方式延迟它:

The result of Sum is an int, so it can't possibly defer it in any meaningful way:

var res2 = no.Sum(a => a * a);
// res2 is now an integer with a value of 55
Console.WriteLine(res2);
no.Add(100);

// how are you expecting an integer to change its value here?
Console.WriteLine(res2);

您可以通过将lambda分配给例如Func<T>:

You can defer the execution (not really defer, but explicitly call it), by assigning the lambda to, for example, a Func<T>:

List<int> no = new List<int>() { 1, 2, 3, 4, 5 };
Func<int> res2 = () => no.Sum(a => a * a);
Console.WriteLine(res2());
no.Add(100);
Console.WriteLine(res2());

这应该正确给出5510055