gpt4 book ai didi

c# - 对 IEnumerable 中的先前值求和

转载 作者:可可西里 更新时间:2023-11-01 03:05:32 26 4
gpt4 key购买 nike

我有一个数字序列:

var seq = new List<int> { 1, 3, 12, 19, 33 };

我想将其转换为一个新序列,其中将数字添加到前面的数字以创建一个新序列:

{ 1, 3, 12, 19, 33 } --> {1, 4, 16, 35, 68 }

我想到了以下内容,但我不喜欢状态变量“count”。我也不喜欢这样的事实,即我使用 Enumerable 值而不对其进行操作。

int count = 1;
var summed = values.Select(_ => values.Take(count++).Sum());

还能怎么办?

最佳答案

这是函数式编程中的常见模式,在 F# 中称为 scan .这就像 C# 的 Enumerable.Aggregate和 F# 的 fold除了它会产生累加器的中间结果以及最终结果。我们可以使用扩展方法在 C# 中很好地实现扫描:

public static IEnumerable<U> Scan<T, U>(this IEnumerable<T> input, Func<U, T, U> next, U state) {
yield return state;
foreach(var item in input) {
state = next(state, item);
yield return state;
}
}

然后按如下方式使用它:

var seq = new List<int> { 1, 3, 12, 19, 33 };
var transformed = seq.Scan(((state, item) => state + item), 0).Skip(1);

关于c# - 对 IEnumerable 中的先前值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6551271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com