如何将int []中的各个元素位置相加?

Chr*_*ris 4 c#

假设我有以下内容:

var a1 = new [] { 2, 7, 9 };
var a2 = new [] { 6, 3, 6 };
Run Code Online (Sandbox Code Playgroud)

我想最终得到:

var sum = new [] { 8, 10, 15 };
Run Code Online (Sandbox Code Playgroud)

到达那里最快捷的方式是什么?

Rom*_*och 6

你可以使用Zip():

var res = a1.Zip(a2, (x, y) => x + y).ToArray();
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用Select():

var res = a1.Select((x, i) => x + a2[i]).ToArray();
Run Code Online (Sandbox Code Playgroud)