Take the n most records with the aggregate

I need help building a linq query that will return a list of usernames that are most fully displayed in the log table for specific messages.

public class Log
{
  public string Username {get; set;}
  public string Message {get; set;}
}

I am interested in the lines where the message is “Created User”, “Modified User” or “Remote User”.

So far I:

    public IQueryable<Log> GetTop5ActiveUsersByManagementMessages()
    {
        return this.ObjectContext.Logs
            .Where(w => w.Message == "Created User" || 
                   w.Message == "Removed User" || 
                   w.Message == "Updated User").Take(5);
    }

I want this to return 5 usernames based on the number or entries of these messages in the log table.

+3
source share
1 answer

To perform this task, use grouping:

this.ObjectContext.Logs
        .Where(w => w.Message == "Created User" || 
               w.Message == "Removed User" || 
               w.Message == "Updated User")
        .GroupBy(w => w.Username)
        .OrderByDescending(g => g.Count())
        .Select(g => g.Key)
        .Take(5);
+5
source

All Articles