Better way of adding(SUM) 'List' of Arrays in C# using lambda expressions or LINQ?

List<double[]> Patterns;

I am using above list to store list of patterns, here each pattern is an array of doubles ( double[] ). Using the bellow code i am adding some patterns.

Patterns.Add(new double[]{1,2,3});
Patterns.Add(new double[]{1,1,1});

In orded to add all the patterns i am using follwing code

if (Patterns.Count > 0)
{
    double[] Result = new double[Patterns[0].Length];
    Patterns.ForEach((pt) =>
    {
        for (int i = 0; i < pt.Length; i++)
        {
            Result[i] += pt[i];
        }
    });
}

Here Result contains

{2,3,4}

Is there a better(Less code) way of doing this? like

double Result[] = Patterns.SomeFunction() or LINQ-Query

Jon Skeet
people
quotationmark

Well, you could use Enumerable.Range to iterate over all the relevant positions in the arrays, and then Sum to sum all the values for each position:

// Variable names changed to follow normal C# conventions
var size = patterns[0].Length;
var result = Enumerable.Range(0, size)
                       .Select(index => patterns.Sum(p => p[index]))
                       .ToArray();

I think that's what you're after... of course, it will break if any of the arrays are shorter than the first one.

people

See more on this question at Stackoverflow