Only functions that return an IEnumerable<T>
can be deferred in Linq (since they can be wrapped in an object that allows deferring).
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);
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());
This should correctly give 55
and 10055
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…