Reputation: 13756
I have a list of objects with field UserID, Property:
I would like to order the list by most shared property value. So if every user has Property= "Popular", that should come up first. If everyone but one user has Property="Second" that should come up second in list... even if its only used once for each user.
I would do distinct() on each possible Property and but that doesnt seem efficient with many possible Property.
Upvotes: 2
Views: 102
Reputation: 160902
You can use a grouping on Property
, order the groups by the number of counts in each group and then flatten the list again using SelectMany()
:
var items = myList.GroupBy(x => x.Property)
.OrderByDescending(g => g.Count())
.SelectMany(g => g);
.ToList();
From your question its not quite clear to me whether you want duplicates to show up or not and if you are at all interested in the UserID
. If not, you can just select the keys of the groups to give you a List<string>
of unique Property values in the desired order:
var props = myList.GroupBy(x => x.Property)
.OrderByDescending(g => g.Count())
.Select(g => g.Key);
.ToList();
Edit:
It seems like this would be more what you are actually are looking for - groups are are ordered by the number of unique users that have a given property.
var props = myList.GroupBy(x => x.Property)
.OrderByDescending(g => g.Select(x=> x.UserID)
.Distinct()
.Count())
.Select(g => g.Key);
.ToList();
Upvotes: 2