4

I have a list of numeric arrays of same sizes. Is it possible to calculate sum of their 1st, 2nd, ..., n-th elements without using for-loops?

This is my code that does it using loops:

static void Main(string[] args)
{
    List<int[]> list = new List<int[]>();
    int n = 4;
    list.Add(new int[] { 1, 2, 3, 4 });
    list.Add(new int[] { 5, 6, 6, 7 });
    list.Add(new int[] { 8, 9, 10, 11 });

    int[] sum = new int[n];
    foreach (int[] array in list)
        for (int i = 0; i < n; i++)
            sum[i] += array[i];
    foreach (int value in sum)
        Console.Write($"{value} ");
    Console.Read();
}
saastn
  • 5,717
  • 8
  • 47
  • 78
  • 1
    `var sum = list.SelectMany(ar => ar).Sum(v => v);`, maybe? (Written here, not tested.) – Jimi Jun 22 '19 at 16:30
  • @Jimi It sums everything and returns an int. – saastn Jun 22 '19 at 16:33
  • Ah, right, you want the *vertical* sums. To add to the answer you already have, a `Enumerable.Range` one: `var sums = Enumerable.Range(0, list[0].Length).Select(col => list.Sum(lst => lst[col]));`. Only working on arrays of the same size. For arrays of different sizes, see [here](https://stackoverflow.com/a/51922659/7444103). – Jimi Jun 22 '19 at 17:05

1 Answers1

6
var sum = list[0].Select((value, i) => list.Sum(sublist => sublist[i]));

Needs special handling for empty list.

Explanation:

sublist => sublist[i]

Given a sublist (i.e. one of the arrays), this selects the i-th element.

list.Sum(sublist => sublist[i])

This query calculates a single number, which is the sum of all i-th elements of the sublists of list.

list[0].Select((value, i) => list.Sum(sublist => sublist[i]))

This selects a number for each entry in list[0]. The number is the sum of all i-th entries in the sublists.

Nico Schertler
  • 32,049
  • 4
  • 39
  • 70