简体   繁体   English

如何获得集合中出现次数最多的值?

[英]How can I get the value with most occurrences in a collection?

I have a list of int? 我有一个int?列表int? that can have 3 different values: null, 1, and 2. I would like to know which of them occurs the most in my list. 可以有3个不同的值:null,1和2。我想知道其中哪个出现在我的列表中最多。 To group them by value I tried to use: 要按值对它们进行分组,我尝试使用:

MyCollection.ToLookup(r => r)

How can I get the value with most occurrence? 如何获得最多的价值?

You don't need a Lookup, a simple GroupBy would do: 您不需要查找,一个简单的GroupBy就可以了:

var mostCommon = MyCollection
  .GroupBy(r => r)
  .Select(grp => new { Value = grp.Key, Count = grp.Count() })
  .OrderByDescending(x => x.Count)
  .First()

Console.WriteLine(
  "Value {0} is most common with {1} occurrences", 
  mostCommon.Value, mostCommon.Count);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何确定哪个值在我的收藏中出现最多? - How can I determine which value occurs the most in my collection? 如何更好地从集合中的集合中获取一个集合? - How can I better get a collection from a collection within a collection? 如何在C#中从优雅集合中创建一个空集合? - How can I create an empty collection from an anonymous collection most elegantly in C#? 如何过滤集合,以便仅获取字段值不为null的行? - How can I filter a collection so I get only the rows where the value of a fields is not null? 如何使用Lambda从子集合中的对象中获取价值 - How can I get value from object in sub-collection with lambda 如何让LINQ返回集合中具有最大值的对象的索引? - How can I get LINQ to return the index of the object which has the max value in a collection? 例外:我如何获得最可能的信息? - Exceptions: How can I get the most possible information? 如何在传递给视图以作为有序列表进行迭代的 ViewModel 集合中获取 jQuery 可选对象的值? - How can I get the value of a jQuery selectable object in a ViewModel collection I passed to my view to be iterated through as an ordered list? 我怎样才能得到这个值? - How can I get this value? 如何为集合中的属性分配特定值? - How can i assign particular value to properties in a collection?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM