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).
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With