Summing the previous values in an IEnumerable

前端 未结 7 2357
有刺的猬
有刺的猬 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:02

    Stephen Swensen's answer is great, scan is exactly what you need. There is another version of scan though that doesn't require a seed, which would be slightly more appropriate for your exact problem.

    This version requires that your output element type is the same as your input element type, which it is in your case, and gives the advantage of not needing you to pass in a 0 and then Skip the first (0) result.

    You can implement this version of scan in C# as follows:

    public static IEnumerable Scan(this IEnumerable Input, Func Accumulator)
    {
        using (IEnumerator enumerator = Input.GetEnumerator())
        {
            if (!enumerator.MoveNext())
                yield break;
            T state = enumerator.Current;
            yield return state;
            while (enumerator.MoveNext())
            {
                state = Accumulator(state, enumerator.Current);
                yield return state;
            }
        }
    }
    

    And then use it as follows:

    IEnumerable seq = new List { 1, 3, 12, 19, 33 };
    IEnumerable transformed = seq.Scan((state, item) => state + item);
    

提交回复
热议问题