Accumulation of subsequences of a sequence using C#/Linq

前端 未结 6 1632
醉梦人生
醉梦人生 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条回答
  •  -上瘾入骨i
    2021-01-20 01:28

    My version which is a modification of what I put in comments and returns an IEnumerable rather than a List but a ToList() will sort that out.

    Should be pretty efficient. And who doesn't like using yield return? ;-)

    public IEnumerable GetCumulativeSequence (IEnumerable input)
    {
        var runningTotal = 0.0;
        foreach (double current in input)
        {
            runningTotal+=current;
            yield return runningTotal;
        }
    }
    
    void Main()
    {
        List list = new List { 10.0, 20.0, 30.0, 40.0 };
        var foo = GetCumulativeSequence(list);
    }
    

    Main advantage of this is that it only does one loop over the input array. and if you don't actually use all of the stuff returned (ie you only look at the first three) then it won't calculate the rest. Potentially useful in longer lists, etc. The same will be said of things like Chris Doggett's answer but not all those here using linq.

提交回复
热议问题