将中位数方法添加到列表中

Ala*_*las 13 c# list median

我想覆盖C#中的List对象,以便添加像Sum或Average这样的Median方法.我已经找到了这个功能:

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;
}
Run Code Online (Sandbox Code Playgroud)

你能告诉我怎么做吗?

Gre*_*reg 21

使用扩展方法,并复制输入的数组/列表.

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在尝试对它进行排序之前,我会检查集合的大小.如果计数为0则抛出异常,如果1返回唯一的值temp [0],否则,排序并执行您的操作. (2认同)

Eri*_*ert 16

不要使用该功能.这是非常有缺陷的.看一下这个:

int[] tempArray = array;     
Array.Sort(tempArray); 
Run Code Online (Sandbox Code Playgroud)

数组是C#中的引用类型.这会对您提供的数组进行排序,而不是副本. 获得数组的中位数不应改变其顺序; 它可能已经被分类到不同的顺序.

使用Array.Copy先使数组的副本,然后进行排序的副本.


Jus*_*ner 6

我肯定会做那些扩展方法:

public static class EnumerableExtensions
{
    public static decimal Median(this IEnumerable<int> list)
    {
        // Implementation goes here.
    }

    public static int Sum(this IEnumerable<int> list)
    {
        // While you could implement this, you could also use Enumerable.Sum()
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过以下方式使用这些方法:

List<int> values = new List<int>{ 1, 2, 3, 4, 5 };
var median = values.Median();
Run Code Online (Sandbox Code Playgroud)

更新

哦......正如Eric提到的,你应该找到另一个中位数的实现.你提供的那个不仅修改原始数组,但是,如果我正确读取它,也将返回一个整数而不是预期的小数.