LoginSignup
0
2

More than 1 year has passed since last update.

【C#】Listの中央値、最頻値を求める

Posted at

中央値

リストの要素が奇数個の場合

var list1 = new List<int> { 1, 2, 5, 4, 3 };
int median1 = list1.OrderBy(x => x).ElementAt(list1.Count() / 2);
Console.WriteLine(median1); // 3

リストの要素が偶数個の場合

var list2 = new List<int> { 1, 2, 5, 4, 3, 6 };
double median2 = list2.OrderBy(x => x).Skip((list2.Count() / 2) - 1).Take(2).Average();
Console.WriteLine(median2); // 3.5

最頻値

最頻値が一つのみの場合

var list3 = new List<int> { 1, 2, 5, 4, 3, 2 };
int mode = list3.GroupBy(x => x).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
Console.WriteLine(mode); // 2

最頻値が複数個存在する場合

var list4 = new List<int> { 1, 2, 5, 4, 3, 5, 2 };
var groups = list4.GroupBy(x => x).Select(g => new { Value = g.Key, Count = g.Count() }).ToList();
int maxCount = groups.Max(g => g.Count);
var modes = groups.Where(g => g.Count == maxCount).Select(g => g.Value).ToList();
Console.WriteLine(string.Join(" ", modes)); // 2 5
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2