I'd like to sort a List
on element counts of IGrouping
s.
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).
var mySortedList = myList.GroupBy(x => x.Name).OrderByDescending(g => g.Count())
.SelectMany(x => x).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With