1

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];
2
  • 1
    You can even LINQ this, but the legibility will be a lot worse. Commented Aug 16, 2017 at 20:46
  • 1
    Two lines of code... Can't be that bad... Commented Aug 16, 2017 at 20:47

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, yes after timing this vs the for loop, the for loop is consistently faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.