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

前端之家收集整理的这篇文章主要介绍了c# – 将中值方法添加到列表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想覆盖C#中的List对象,以便添加一个中值方法,如Sum或Average.我已经发现这个功能: @H_502_2@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; }

你能告诉我怎么做吗

解决方法

使用扩展方法,并复制输入的数组/列表. @H_502_2@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]; } }

猜你在找的C#相关文章