C# 关于 IEnumerable.Aggregate
我做了一些关于 IList
List<int> Data1 = new List<int> { 1,0,0,0,0};
var result = Data1.Aggregate<int>((total, next) => total + total);
结果是16
。
我预计它是 32
。
有人可以解释一下吗?
I did some tests about IList<T>.Aggregate()
, but the answer does not make sense to me.
List<int> Data1 = new List<int> { 1,0,0,0,0};
var result = Data1.Aggregate<int>((total, next) => total + total);
The result is 16
.
I expected it to be 32
.
Can someone explain?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Aggregate
不会对列表中的第一个元素运行回调。相反,第一个元素用作累加器的初始值(
total
)。因此,您的回调仅运行四次,而不是五次,并且 24 = 16。
Aggregate
doesn't run its callback for the first element in the list.Rather, the first element is used as the initial value for the accumulator (
total
).Therefore, your callback only runs four times, not five, and 24 = 16.