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?
There's a time for generality, and there's a time for solving the problem actually posed. This is one of the latter times. If you want to make a method that turns a sequence of doubles into a sequence of partial sums, then just do that:
Easy. No messing around with aggregates and complicated queries and whatnot. Easy to understand, easy to debug, easy to use:
Now, I note that if that is user input then double.Parse can throw an exception; it might be a better idea to do something like:
and now you don't get an exception if the user makes a typing mistake; you get nulls.
Here's a way of doing it using LINQ:
In LINQPad:
This is actually pretty straightforward to generalize using generator. Here is a new extension method called
Accumulate
that works like a combination ofSelect
andAggregate
. It returns a new sequence by applying a binary function to each element in the sequence and accumulated value so far.I had a similar requirement some time ago. Basically, I needed to do an aggregation, but I also needed to select each intermediate value. So I wrote an extension method named
SelectAggregate
(probably not the most appropriate name, but I couldn't find anything better then) that can be used like that:Here's the code :
Why does it need to be LINQ?