saastn
saastn

Reputation: 6015

How to sum elements of unknown number of arrays using LINQ?

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();
}

Upvotes: 4

Views: 3462

Answers (1)

Nico Schertler
Nico Schertler

Reputation: 32587

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.

Upvotes: 6

Related Questions