本文介绍了使用C#/Linq累积序列的子序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据以下要求找到一种更好的处理数字序列的方法:sequence[i]的值是它自己的值加上sequence[0]sequence[i-1]的累加之和.

I'm trying to find a better way of processing a sequence of numbers based on the following requirement:the value of sequence[i] is the sum of its own value plus the accumulation from sequence[0] to sequence[i-1].

例如:如果序列是列表

For example:if the sequence is a list

List<double> list = new List<double> { 10.0, 20.0, 30.0, 40.0 };

输出结果应该是

list[0] = 10.0
list[1] = 20.0 + 10.0
list[2] = 30.0 + 10.0 + 20.0
list[3] = 40.0 + 10.0 + 20.0 + 30.0

我知道使用多次迭代的蛮力方式,但我想知道是否必须有更好的解决方案(也许使用LINQ).

I know the brute force way which uses multiple iterations, but I wonder there must be some better solution (maybe with LINQ).

推荐答案

假定您有权使用LINQ:

Assuming you have access to LINQ:

using System.Linq;

List<int> numbers = new List<int> {10, 20, 30, 40};
List<int> runningTotals = new List<int>(numbers.Count);

numbers.Aggregate(0, (sum, value) => {
    sum += value;
    runningTotals.Add(sum);
    return sum;
});

这篇关于使用C#/Linq累积序列的子序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:39