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. I’d like to sum all 500 of these arrays, to give me a single array, 2048 elements long, where each element is the sum of all the same positions in all the other arrays.
Obviously this is trivial in imperative code:
int[] sums = new int[myList[0].Length]; foreach(int[] array in myList) { for(int i = 0; i < sums.Length; i++) { sums[i] += array[i]; } }
But I was wondering if there was a nice Linq or Enumerable.xxx technique?
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:
That’s kind of ugly…but I think the statement version would be even worse.