Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a histogram for a list of int in C# [duplicate]

Tags:

c#

linq

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.

like image 512
Simon Avatar asked Dec 09 '22 00:12

Simon


1 Answers

 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
}
like image 193
Tim Schmelter Avatar answered Mar 06 '23 15:03

Tim Schmelter