How to build a histogram for a list of int in C#
c#, linq
Solution
int highestAppearanceNum = demoList.GroupBy(i => i)
.OrderByDescending(grp => grp.Count())
.Select(grp => grp.First())
.First();
Edit: If you also want to know which number appears how often:
var appearances = demoList.GroupBy(i => i)
.OrderByDescending(grp => grp.Count())
.Select(grp => new { Num = grp.Key, Count = grp.Count() });
if (appearances.Any())
{
int highestAppearanceNum = appearances.First().Num; // 1
int highestAppearanceCount = appearances.First().Count; // 5
}
Problem
Possible Duplicate: Find the most frequent numbers in an array using LINQ I have a list of int, `List<int> demoList`, which is something like `{1, 2, 1, 1, 1, 3, 2, 1}` and I want to write a LINQ statement for obtaining the number with the highest number of appearences from that list, which in my case is `1`.