Search code examples
c#linq

Adding/summing two arrays


I've encountered a purely hypothetical problem which feels like it has an easy solution if I find the right linq method...

I have two arrays of ints and I know they are the same size. I want to create a third array of the same size where the elements in the third array are the sum of the elements in the first two arrays in the corresponding position.

Below is a method that should show what I want to do.

public static int[] AddArrays(int[] a, int[] b)
{
    int[] newArray = new int[a.Length];
    for (int i = 0; i<a.Length; i++)
    {
        newArray[i]=a[i]+b[i];
    }
    return newArray;
}

Are there any Linq methods that I can just use like

return a.DoStuff(b, (x,y) => x+y)

or something like that?

I should note that this probably falls in the category of homework since the original problem came from a website I was looking at (though I can't find a direct link to the problem) and not as a question I need for work or anything.

If no simple method exists then what is the most Linqy way to do this? an array.each would seem to have the problem of not being able to index the second array easily to add the values to the one you are iterating through leading me to wonder if Linq would be any help at all in that situation...


Solution

  • Zip it :)

    var a = new int[] {1,2,3 };
    var b = new int[] {4,5,6 };
    a.Zip(b, (x, y) => x + y)