Summing the previous values in an IEnumerable

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

    Just to offer another alternative, albeit not really LINQ, you could write a yield-based function to do the aggregation:

    public static IEnumerable SumSoFar(this IEnumerable values)
    {
      int sumSoFar = 0;
      foreach (int value in values)
      {
        sumSoFar += value;
        yield return sumSoFar;
      }
    }
    

    Like BrokenGlass's this makes only a single pass over the data although unlike his returns an iterator not a list.

    (Annoyingly you can't easily make this generic on the numeric type in the list.)

提交回复
热议问题