List most frequent items in the database using LINQ

2

I would like to list on the screen, type a ranking, the most frequent items in the database table through its name, for example:

John appears 6 times; Joseph appears 4 times; Maria appears once.

Would anyone help me?

asked by anonymous 26.02.2016 / 20:12

1 answer

2

There is not much secret:

var grupos = db.Entidade
                  .GroupBy(e => e.Nome)
                  .OrderByDescending(g => g.Count())
                  .ToList();

Each element of grupos is a special enumeration (called Grouping ) that has a Key attribute (in this case, the name of the person). That is, to get the records, you can do this:

foreach (var registros in grupos) {
    Console.WriteLine("Nome: " + registros.Key);
    foreach (registro in registros)
    {
        // Aqui vai uma lógica para lidar com cada registro.
    }
}
    
26.02.2016 / 20:19