[英]In C#, how can I order a list after its grouped by size of the list?
Lets say I have a collection of car objects 可以说我有一些汽车用品
3 blue cars 3辆蓝色汽车
10 yellow car 10黄车
5 red cars 5辆红色轿车
List<Car> cars = GetList();
var groupBy = cars.GroupBy(r=>r.Color);
I now want to sort the groupBy grouped collection in descending order so I first get the yellow cars, then red and then blue when i loop through the list 现在,我想按降序对groupBy分组的集合进行排序,这样当我遍历列表时,我首先得到黄色的汽车,然后是红色的,然后是蓝色的
What is the correct way to sort a grouped list by the size of the collection in that entry of the group by list? 在按列表分组的条目中,按集合的大小对分组列表进行排序的正确方法是什么?
var result = cars.GroupBy(r=>r.Color).OrderByDescending(g => g.Count());
When you group a collection, you will get a IEnumerable<Grouping<TKey, TValue>>
collection which has the Key
property and Value
property. 对集合进行IEnumerable<Grouping<TKey, TValue>>
,将获得IEnumerable<Grouping<TKey, TValue>>
集合,该集合具有Key
属性和Value
属性。 The Key
is the value which you have grouped and the Value
is the entire object grouped by the Key
. Key
是您分组的Value
,而Value
是按Key
分组的整个对象。 You also have all extensions for IEnumerable
. 您还具有IEnumerable
所有扩展名。
In your case, you could just call the OrderByDescending
method passing the Count()
method from group colelction, for sample: 在您的情况下,您可以只调用OrderByDescending
方法,并从组集合中传递Count()
方法作为示例:
var result = cars.GroupBy(r=>r.Color).OrderByDescending(x => x.Count());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.