Search code examples
c#arrayslinqcumulative-sum

using LINQ to find the cumulative sum of an array of numbers in C#


I have a csv string containing doubles (e.g "0.3,0.4,0.3"), and I want to be able to output a double array containing the cumulative sum of these numbers (e.g [0.3,0.7,1.0]).

So far, I have

double[] probabilities = textBox_f.Text.Split(new char[]{','}).Select(s => double.Parse(s)).ToArray();

which gives the numbers as an array, but not the cumulative sum of the numbers.

Is there any way to continue this expression to get what I want, or do I need to use iteration to create a new array from the array I already have?


Solution

  • var input=new double[]{ ... }
    double sum=0;
    
    var output=input
        .Select(w=>sum+=w);