通过Lambda按列表分组 [英] Group By List with Lambda
本文介绍了通过Lambda按列表分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的对象:
public class obj
{
public Int32 id { get; set; }
public Int32 source { get; set; }
}
现在我有一个列表:10个对象的List<obj>
,其中5个对象的源设置为100
,3个对象的源设置为200
,2个对象的源设置为2500
Now I have a list: List<obj>
of 10 objects, 5 of them have source set to 100
, 3 have source set to 200
and 2 have source set to 2500
我需要按来源分组,这将导致三个项目100
,200
和2500
.
我还需要按计数顺序进行排序,例如:
I need to group by the source which will result in three items 100
, 200
and 2500
.
Also I need to order by count, like this:
5 100
3 200
2 2500
最终结果是我想获得源计数最高的源,在这种情况下为100
The end result is that I want to get the source with the top count, which in this case will be 100
推荐答案
这将为您提供源源不断的信息:
This will give you source with top count:
int topSource = list.GroupBy(o => o.source)
.OrderByDescending(g => g.Count())
.First()
.Key;
说明
- 按源值对项目进行分组(它将创建三个组)
- 按商品分组的订单组在每个组中
- 选择第一个组(它将具有最大数量的项目)
- 获取分组键(这是源值)
这篇关于通过Lambda按列表分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文