c# - Summing the previous values in an IEnumerable -
i have sequence of numbers:
var seq = new list<int> { 1, 3, 12, 19, 33 };
and want transform new sequence number added preceding numbers create new sequence:
{ 1, 3, 12, 19, 33 } --> {1, 4, 16, 35, 68 }
i came following, dislike state variable 'count'. dislike fact i'm using values enumerable without acting on it.
int count = 1; var summed = values.select(_ => values.take(count++).sum());
how else done?
this common pattern in functional programming in f# called scan. it's c#'s enumerable.aggregate , f#'s fold except yields intermediate results of accumulator along final result. can implement scan in c# nicely extension method:
public static ienumerable<u> scan<t, u>(this ienumerable<t> input, func<u, t, u> next, u state) { yield return state; foreach(var item in input) { state = next(state, item); yield return state; } }
and use follows:
var seq = new list<int> { 1, 3, 12, 19, 33 }; var transformed = seq.scan(((state, item) => state + item), 0).skip(1);
Comments
Post a Comment