我有兴趣使用Linq将数组乘以一个因子.
我目前的代码是:
public static double[] multiply(double[] x, double factor)
{
if (x == null) throw new ArgumentNullException();
double[] result = new double[x.Length];
for (int i = 0; i < x.Length; i++)
{
result[i] = x[i] * factor;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
在Linq中执行此操作的最有效方法是什么,它会提供更好的性能吗?
Hab*_*bib 11
你可以通过LINQ这样做:
double[] result = x.Select(r=> r * factor).ToArray();
Run Code Online (Sandbox Code Playgroud)
会有效吗?不太确定.但它只是简洁,即使有性能增益也可以忽略不计.LINQ内部使用循环,所以你的方法可能是:
public static double[] multiply(double[] x, double factor)
{
if (x == null) throw new ArgumentNullException();
return x.Select(r => r * factor).ToArray();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3869 次 |
| 最近记录: |