Summing the previous values in an IEnumerable

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

    To use Linq and only iterate over the list once you could use a custom aggregator:

    class Aggregator
    {
        public List List { get; set; }
        public int Sum { get; set; }
    }
    

    ..

    var seq = new List { 1, 3, 12, 19, 33 };
    var aggregator = new Aggregator{ List = new List(), Sum = 0 };
    var aggregatorResult = seq.Aggregate(aggregator, (a, number) => { a.Sum += number; a.List.Add(a.Sum); return a; });
    var result = aggregatorResult.List;
    

提交回复
热议问题