加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将中值方法添加到列表

发布时间:2020-12-15 06:24:49 所属栏目:百科 来源:网络整理
导读:我想覆盖C#中的List对象,以便添加一个中值方法,如Sum或Average.我已经发现这个功能: public static decimal GetMedian(int[] array){ int[] tempArray = array; int count = tempArray.Length; Array.Sort(tempArray); decimal medianValue = 0; if (count
我想覆盖C#中的List对象,以便添加一个中值方法,如Sum或Average.我已经发现这个功能:
public static decimal GetMedian(int[] array)
{
    int[] tempArray = array;
    int count = tempArray.Length;

    Array.Sort(tempArray);

    decimal medianValue = 0;

    if (count % 2 == 0)
    {
        // count is even,need to get the middle two elements,add them together,then divide by 2
        int middleElement1 = tempArray[(count / 2) - 1];
        int middleElement2 = tempArray[(count / 2)];
        medianValue = (middleElement1 + middleElement2) / 2;
    }
    else
    {
        // count is odd,simply get the middle element.
        medianValue = tempArray[(count / 2)];
    }

    return medianValue;
}

你能告诉我怎么做吗

解决方法

使用扩展方法,并复制输入的数组/列表.
public static decimal GetMedian(this IEnumerable<int> source)
{
    // Create a copy of the input,and sort the copy
    int[] temp = source.ToArray();    
    Array.Sort(temp);

    int count = temp.Length;
    if (count == 0)
    {
        throw new InvalidOperationException("Empty collection");
    }
    else if (count % 2 == 0)
    {
        // count is even,average two middle elements
        int a = temp[count / 2 - 1];
        int b = temp[count / 2];
        return (a + b) / 2m;
    }
    else
    {
        // count is odd,return the middle element
        return temp[count / 2];
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读