C#計算眾數
阿新 • • 發佈:2018-12-06
public class CalculateModeTool<T> where T : struct { // 源資料 private List<T> source; // 建構函式 public CalculateModeTool(List<T> source) { this.source = source; } // 計算眾數 public Dictionary<T, int> Calculate() { Dictionary<T, int> dictionary = new Dictionary<T, int>(); foreach (T item in source) { if (!dictionary.ContainsKey(item)) { dictionary.Add(item, 1); } else { dictionary[item]++; } } // 眾數不存在 int first = dictionary.OrderBy(m => m.Value).First().Value; int last = dictionary.OrderBy(m => m.Value).Last().Value; if (last == 1) { return null; } if (last == first) { return null; } // 獲取眾數 Dictionary<T, int> result = new Dictionary<T, int>(); foreach (KeyValuePair<T, int> kvp in dictionary) { if (kvp.Value == last) { result.Add(kvp.Key, kvp.Value); } } return result; } }
class Program { static void Main(string[] args) { List<int> source = new List<int>() { 1, 1, 2, 2, 0, 1, 3, 3 }; CalculateModeTool<int> tool = new CalculateModeTool<int>(source); Dictionary<int, int> dictionary = tool.Calculate(); if (dictionary == null) { Console.WriteLine("眾數不存在"); } else { foreach (KeyValuePair<int, int> kvp in dictionary) { Console.WriteLine(kvp.Key); } } Console.ReadKey(true); } }