Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply a native C# array by a factor using Linq

Tags:

c#

linq

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?

like image 966
C Mars Avatar asked Apr 23 '14 15:04

C Mars


1 Answers

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();
}
like image 107
Habib Avatar answered Nov 12 '22 17:11

Habib