Search code examples
c#arrayslambda

Using the input of a Lambda expression as an index for a separate array in c#


I'm currently trying to make a calculator that calculates Mean / Median / IQR / Standard Deviation / Variance of a set of data and a set of frequencies. To get the Mean of a set of data, i had intended to use the Sum() function and Lambda expressions, however i ran into a problem with this code below.

public double stat_getMeanGrouped(double[] dataset, double[] frequency)
{
    return dataset.Sum(x => x * frequency[int.Parse(x.toString)] / (double)frequency.Sum();
}

stat_getMeanGrouped(new double[] {1,2,3}, new double[] {1,1,1}); should return 2 however returns an index outside of range exception.

I understand why the error is happening, i just need help amending it.


Solution

  • You need to use the index, you can get it from the Select overload, if you want to use LINQ:

    public static double stat_getMeanGrouped(double[] dataset, double[] frequency)
    {
        return dataset
            .Select((value, index) => (Value: value, Index: index))
            .Where(x => x.Index < frequency.Length) // just to be sure
            .Sum(x => x.Value * frequency[x.Index]) / (double)frequency.Sum();
    }