I would like to override the List object in C# in order to add a Median method like Sum or Average. I already found this function:
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;
}
Can you tell me how to do that?
The median is the number in the middle {2, 3, 11, 13, 26, 34, 47}, which in this instance is 13 since there are three numbers on either side. To find the median value in a list with an even amount of numbers, one must determine the middle pair, add them, and divide by two.
median() method calculates the median (middle value) of the given data set. This method also sorts the data in ascending order before calculating the median. Tip: The mathematical formula for Median is: Median = {(n + 1) / 2}th value, where n is the number of values in a set of data.
In Python, the statistics. median() function is used to calculate the median value of a data set. The median() method takes in one parameter: the data list. When you call the median() method, it will order a list of values and find its middle value.
Use an extension method, and make a copy of the inputted array/list.
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];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With