1

I have a list:

dave
maggie
john
stuart
john
john
dave
john
maggie
maggie

My desired result would be:

john
john
john
john
maggie
maggie
maggie
dave
dave
stuart
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Lukas Morkunas
  • 316
  • 3
  • 12

1 Answers1

6

First I group them. Then order them by the count from each group. Lastly use SelectMany to get a flat structure from each individual name in the groups.

var myList = new List<string>()
{
    "dave",
    "maggie",
    "john",
    "stuart",
    "john",
    "dave",
    "john",
};

var result = myList
    .GroupBy(x => x)
    .OrderByDescending(x => x.Count())
    .SelectMany(x => x)
    .ToList();
NotFound
  • 5,005
  • 2
  • 13
  • 33
  • 1
    @Stefan yes. `SelectMany` takes a function returning a `IEnumerable` and `GroupBy` returns an `IEnumerable`. – NotFound Oct 03 '19 at 07:20