List most frequent items in the database using LINQ

Asked

Viewed 79 times

2

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

John appears 6 times; Joseph appears 4 times; Mary appears 1 time.

Someone would help me?

Obs: I’m making a web application using Asp.net mvc 5.

Thank you!!

1 answer

2


It’s not much of a secret:

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.