Calculate median in c#

前端 未结 12 1491
别跟我提以往
别跟我提以往 2020-11-29 23:35

I need to write function that will accept array of decimals and it will find the median.

Is there a function in the .net Math library?

12条回答
  •  野性不改
    2020-11-30 00:13

    My 5 cents (because it appears more straightforward/simpler and sufficient for short lists):

    public static T Median(this IEnumerable items)
    {
        var i = (int)Math.Ceiling((double)(items.Count() - 1) / 2);
        if (i >= 0)
        {
            var values = items.ToList();
            values.Sort();
            return values[i];
        }
    
        return default(T);
    }
    

    P.S. using "higher median" as described by ShitalShah.

提交回复
热议问题