Accumulation of subsequences of a sequence using C#/Linq

前端 未结 6 1704
醉梦人生
醉梦人生 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:45

    Here is another way similar to one of the posts, but this one is self-contained:

    // C#
    Enumerable.Range(1, 100)
    .Aggregate(new List{0},
      (acc, x) => { acc.Add(acc.Last() + x); return acc; })
    .Dump(); // Dump using LINQPad; ans: 5050
    

    If we switch to int64, and use 10,000,000 as the upper bound, and read the final accumulated result, the code executes in about 450 milli-seconds on a Corei5 with a final output of:

    50000005000000

    Incidentally, for an upper bound of 1,000,000 the execution is about 40 milli-seconds, so increasing the size by 10 increased the time by 10.

提交回复
热议问题