如何在Linq查询中计算一系列整数的运行总和? [英] How to compute a running sum of a series of ints in a Linq query?
问题描述
我正在尝试使用linq查询将IEnumerable<int>
转换为另一个IEnumerable<int>
,其中结果中的每个int是从初始列表到该位置为止的所有int的总和.
I am trying to come up with a linq query to convert an IEnumerable<int>
to another IEnumerable<int>
, where each int in the result is the sum of all the ints up to that position from the initial list:
给定int[] a
我需要int[] b
其中b[0] = a[0], b[1] = a[0] + a[1], b[2] = a[0] + a[1] + a[2]
等等
Given int[] a
I need int[] b
Where b[0] = a[0], b[1] = a[0] + a[1], b[2] = a[0] + a[1] + a[2]
and so on
或者,上面的总和可以写为b[1] = b[0] + a[1], b[2] = b[1] + a[2]
,依此类推,但是我看不出有什么帮助.
Alternatively, the sums above can be written as b[1] = b[0] + a[1], b[2] = b[1] + a[2]
and so on, but I don't see how that would help.
我当然可以通过for
循环执行此操作,但是我从查询中获得了a []序列,并且我认为如果我继续执行该查询而不是突然在其中添加for
会更好. :)
I can, of course, do this with a for
loop, but I obtain the a[] sequence from a query and I thought it would look nicer if I continue that query instead of suddenly adding a for
there :)
推荐答案
好吧,尽管它很棘手,但您可以很容易地实现副作用.
Well, you can do it with side effects easily enough, although it's pretty icky...
int sum = 0;
int[] b = a.Select(x => (sum += x)).ToArray();
如果框架提供了一种运行聚合"来封装它,那将是很好的选择,但据我所知,它还没有.
It would be nice if the framework provided a sort of "running aggregate" to encapsulate this, but it doesn't as far as I'm aware.
这篇关于如何在Linq查询中计算一系列整数的运行总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!