I am interested in using Linq to multiply an array by a factor.
My current code is:
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;
}
What is the most efficient method of doing this in Linq, and will it provide better performance?
You can do that through LINQ like:
double[] result = x.Select(r=> r * factor).ToArray();
Would it be efficient ? not really sure. But it is just concise, even if there is a performance gain it would be negligible. LINQ internally uses loops, So your method could be:
public static double[] multiply(double[] x, double factor)
{
if (x == null) throw new ArgumentNullException();
return x.Select(r => r * factor).ToArray();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With