本文介绍了如何建立一个柱状图为int在C#中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
}

这篇关于如何建立一个柱状图为int在C#中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 04:50