我想在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;
}
你能告诉我如何做到这一点吗?
GetMedian
方法将具有对传递给该方法的数组进行排序的副作用。由于数组是引用类型,将数组分配给一个新变量(tempArray)不会创建一个新的数组。 - Greg