int[] array = {1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 5, 6, 6, 7, 8};
var sortedByFrequency = array
.GroupBy(o => o)
.OrderByDescending(o => o.Count())
.ThenByDescending(o => o.Key)
.SelectMany(o => o)
.ToArray();
Console.WriteLine(string.Join(",",sortedByFrequency.Select(o => o.ToString())));
//4,4,4,4,1,1,1,6,6,3,3,8,7,5,2
var arr = new int[] { 1, 1, 1, 2, 3, 3, 4, 4, 4, 4, 5, 6, 6, 7, 8 };
var index = arr.GroupBy(x => x).ToDictionary(x => x.Key, x => x.Count());
var result = arr.OrderByDescending(x => x, new CountComparer(index)).ToArray();
class CountComparer : IComparer<int>
{
private readonly IReadOnlyDictionary<int, int> _index;
public CountComparer(IReadOnlyDictionary<int, int> index)
{
_index = index;
}
public int Compare(int x, int y)
{
var comparsion = _index[x].CompareTo(_index[y]);
if (comparsion == 0)
return x.CompareTo(y);
return comparsion;
}
}