How do I sum a list<> of arrays

Edit: Ouch...This became a bit harder while I wasn't looking. Changing requirements can be a real PITA.

Okay, so take each position in the array, and sum it:

var sums = Enumerable.Range(0, myList[0].Length)
           .Select(i => myList.Select(
                     nums => nums[i]
                  ).Sum()
           );

That's kind of ugly...but I think the statement version would be even worse.


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.

Tags:

C#

Linq