Summing the previous values in an IEnumerable

前端 未结 7 2300
有刺的猬
有刺的猬 2021-01-04 02:36

I have a sequence of numbers:

var seq = new List { 1, 3, 12, 19, 33 };

and I want to transform that into a new sequence where

相关标签:
7条回答
  • 2021-01-04 03:04

    This is a common pattern in functional programming which in F# is called scan. It's like C#'s Enumerable.Aggregate and F#'s fold except that it yields the intermediate results of the accumulator along with the final result. We can implement scan in C# nicely with an 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 then use it as follows:

    var seq = new List<int> { 1, 3, 12, 19, 33 };
    var transformed = seq.Scan(((state, item) => state + item), 0).Skip(1);
    
    0 讨论(0)
提交回复
热议问题