You can do:
- Group by each item
- Order by descending based on group count
- select unique item based on group key
Like:
List<int> list = new List<int> { 1, 2, 3, 2, 1, 6, 2 };
var query = list.GroupBy(item => item)
.OrderByDescending(grp => grp.Count())
.Select(grp => grp.Key);
foreach (var item in query)
{
Console.WriteLine(item);
}
EDIT:
If you don’t want unique item, but all the items based on their occurrence then use:
var query = list.GroupBy(item => item)
.OrderByDescending(grp => grp.Count())
.SelectMany(grp => grp);
SelectMany
will flatten the list and give you an output like:
2
2
2
1
1
3
6
2
solved Ordering list of integers by the count of each element in C# [closed]