Search code examples
c#linq

Ordering list of integers by the count of each element in C#


I would like to order the elements of a list of integers by how many times the integer appears in the list.

So the first element of the result list should be the most common element in the original list, the second is the second most common, and so on. Each integer should only be included once in the result list, not as many times as the original list contains it. Secondary order is not important.

For example, for 1,2,3,2,1,6,2, I would like to get 2,1,3,6 (2 appears thrice, 1 appears twice, 3 and 6 both appear only once).


Solution

  • 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