简体   繁体   English

列表中最大的子组,但是确定性的

[英]Largest sub-group in a list, but deterministic

In a list of eg 100 items with an integer value IntValue , I can easily group by these values. 在具有整数值IntValue的例如100个项目的列表中,我可以轻松地按这些值进行分组。
var groupby = list.GroupBy(i => i.IntValue);

What is the best Linq-way to find the largest group in the groupby variable now? 现在在groupby变量中找到最大组的最佳Linq方式是什么?

It must be deterministic, so when there are two largest groups in the list with the same number of items, I would want to select te lowest value of IntValue . 它必须是确定性的,因此当列表中有两个最大的组且项目数相同时,我想选择IntValue

Just do some ordering and take the first one: 只需点些菜,然后选择第一个即可:

var group = groupby.OrderByDescending(g => g.Count())
                   .ThenBy(g => g.Key)
                   .First();

You could achieve the same using syntax-based query: 您可以使用基于语法的查询来实现相同的目的:

var group = (from g in groupby
             order g by g.Count() descending, g.Key
             select g).First();

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM