Accumulation of subsequences of a sequence using C#/Linq

前端 未结 6 1630
醉梦人生
醉梦人生 2021-01-20 01:13

I\'m trying to find a better way of processing a sequence of numbers based on the following requirement: the value of sequence[i] is the sum of its own value pl

6条回答
  •  别那么骄傲
    2021-01-20 01:49

    I built a general purpose (with lots of variations) extension method based on the APL scan operator (analogous to how Aggregate is essentially the APL reduce operator) that returns the intermediate results of the sequence of operations:

    public static IEnumerable Scan(this IEnumerable src, TResult seed, Func combine) {
        foreach (var s in src) {
            seed = combine(seed, s);
            yield return seed;
        }
    }
    

    Which can then be used like:

    var ans = list.Scan(0.0, (a, d) => a+d).ToList();
    

提交回复
热议问题