Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list based on group count

Tags:

c#

linq

group-by

I'd like to sort a List on element counts of IGroupings.

And that's it, the list should ideally be the same. I would compromise with a new list, but then the elements should be the very same original objects, not copies (however shallow) and definitely not anonymous objects.

Specifically: We have an entity with many properties, and a list of objects of this type. We'd like to (1) group the objects by certain properties (name, address, ...) then (2) count the number of elements in each group. Finally we'd like to (3) reorder the list based on these counts by placing the elements that are part of the larger groups first.

Note: Our main issue is that we can't seem to find a way to keep a reference to the original objects in the elements of the groups. Indeed all we can select in the Linq query is the grouping key (or properties of the key) and nothing else is exposed by IGrouping. We can't figure out how to associate a group element with an element of the list either, short of looking at the data (and even then, we'd need the primary key, which we can't add to the grouping key or it would defeat the purpose of the grouping to begin with).

like image 408
tne Avatar asked Dec 20 '22 22:12

tne


1 Answers

var mySortedList = myList.GroupBy(x => x.Name).OrderByDescending(g => g.Count())
                       .SelectMany(x => x).ToList();
like image 118
Tim S. Avatar answered Dec 22 '22 10:12

Tim S.