Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

c# - Sort list based on group count

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
var mySortedList = myList.GroupBy(x => x.Name).OrderByDescending(g => g.Count())
                       .SelectMany(x => x).ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...