Reputation: 196469
Lets say I have a collection of car objects
3 blue cars
10 yellow car
5 red cars
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
What is the correct way to sort a grouped list by the size of the collection in that entry of the group by list?
Upvotes: 0
Views: 187
Reputation: 3188
var result = cars.GroupBy(r=>r.Color).OrderByDescending(g => g.Count());
Upvotes: 3
Reputation: 38598
When you group a collection, you will get a IEnumerable<Grouping<TKey, TValue>>
collection which has the Key
property and Value
property. The Key
is the value which you have grouped and the Value
is the entire object grouped by the Key
. You also have all extensions for IEnumerable
.
In your case, you could just call the OrderByDescending
method passing the Count()
method from group colelction, for sample:
var result = cars.GroupBy(r=>r.Color).OrderByDescending(x => x.Count());
Upvotes: 0