Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accumulation of subsequences of a sequence using C#/Linq

Tags:

c#

linq

sequence

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 };

the output result should be

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

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

like image 307
esun203 Avatar asked Nov 30 '22 15:11

esun203


1 Answers

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;
});
like image 54
Chris Doggett Avatar answered Dec 02 '22 04:12

Chris Doggett