不应该在LINQ中推迟求和方法

Med*_*dia -1 c# linq

我有以下代码:

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);
Run Code Online (Sandbox Code Playgroud)

我期待以下结果:

55
10055

但都是55岁

55
55

我在这里看到的是关于延期评估,但没有帮助.Sum是一种扩展方法,但结果不是我提到的.为什么?

Jcl*_*Jcl 8

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

结果Sumint,所以它不可能以任何有意义的方式推迟它:

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);
Run Code Online (Sandbox Code Playgroud)

您可以通过将lambda分配给例如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());
Run Code Online (Sandbox Code Playgroud)

这应该正确给予5510055