How do I sum a list<> of arrays

后端 未结 7 1405
故里飘歌
故里飘歌 2021-02-04 08:24

I have a List< int[] > myList, where I know that all the int[] arrays are the same length - for the sake of argument, let us say I have 500 arrays, each is 2048 elements long

7条回答
  •  灰色年华
    2021-02-04 08:55

    EDIT: I've left this here for the sake of interest, but the accepted answer is much nicer.

    EDIT: Okay, my previous attempt (see edit history) was basically completely wrong...

    You can do this with a single line of LINQ, but it's horrible:

    var results = myList.SelectMany(array => array.Select(
                                                   (value, index) => new { value, index })
                        .Aggregate(new int[myList[0].Length],
                                   (result, item) => { result[item.index] += value; return result; });
    

    I haven't tested it, but I think it should work. I wouldn't recommend it though. The SelectMany flattens all the data into a sequence of pairs - each pair is the value, and its index within its original array.

    The Aggregate step is entirely non-pure - it modifies its accumulator as it goes, by adding the right value at the right point.

    Unless anyone can think of a way of basically pivoting your original data (at which point my earlier answer is what you want) I suspect you're best off doing this the non-LINQ way.

提交回复
热议问题