Chris
Chris

Reputation: 28064

How can I sum the individual element positions in an int[]?

Suppose I have the following:

var a1 = new [] { 2, 7, 9 };
var a2 = new [] { 6, 3, 6 };

I want to end up with:

var sum = new [] { 8, 10, 15 };

What's the quickest way to get there?

Upvotes: 4

Views: 47

Answers (1)

Roman
Roman

Reputation: 12171

You can use Zip():

var res = a1.Zip(a2, (x, y) => x + y).ToArray();

Also, you can use Select():

var res = a1.Select((x, i) => x + a2[i]).ToArray();

Upvotes: 6

Related Questions