假设我有一个函数c [i] = f(x [i],y [i])。我有相等长度的输入值数组x和y,我想最后计算数组c的值。我如何使用LINQ做到这一点?
即无需写:
c = new double[x.Length];
for (int i = 0; i < x.Length; i++)
{
c[i] = f(x[i], y[i]);
}
最佳答案
使用Zip
方法,例如:
int[] x = { 1, 2, 3 };
int[] y = { 4, 5, 6 };
var result = x.Zip(y, (i, j) => i + j);
或者如果您已经具有足够参数的方法,则只需使用:
var result = x.Zip(y, Function);
// in this sample Function looks like:
static int Function(int x, int y)
{
return x + y;
}
关于c# - LINQ:评估一个函数,其中数组元素按索引匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9803298/