obl obl - 2 years ago 124
C# Question

Add values of int array to values of another int array C#

I have two int arrays of the same length 5, array1 & array2. I want to add the values of array2 to the values of array1. Is there a faster/more concise way to do this other than a simple for loop? Maybe using LINQ?

for (int i = 0; i < 5; i++)
array1[i] += array2[i];

Answer Source

If you want to use LINQ, you can use Enumerable.Zip():

array1 = array1.Zip(array2, (a, b) => a + b).ToArray();

I doubt that it's faster though, and "more concise" is also questionable. For one thing, it has to allocate a whole new array instead of updating in-place like your for loop does.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download