LINQ中不应推迟求和方法

编程入门 行业动态 更新时间:2024-10-26 10:28:36
本文介绍了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());

这应该正确给出55和10055

更多推荐

LINQ中不应推迟求和方法

本文发布于:2023-11-25 12:33:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1629764.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不应   方法   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!