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 pl
My version which is a modification of what I put in comments and returns an IEnumerable rather than a List but a ToList() will sort that out.
Should be pretty efficient. And who doesn't like using yield return
? ;-)
public IEnumerable GetCumulativeSequence (IEnumerable input)
{
var runningTotal = 0.0;
foreach (double current in input)
{
runningTotal+=current;
yield return runningTotal;
}
}
void Main()
{
List list = new List { 10.0, 20.0, 30.0, 40.0 };
var foo = GetCumulativeSequence(list);
}
Main advantage of this is that it only does one loop over the input array. and if you don't actually use all of the stuff returned (ie you only look at the first three) then it won't calculate the rest. Potentially useful in longer lists, etc. The same will be said of things like Chris Doggett's answer but not all those here using linq.