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
.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With