Take n most records with aggregate
I need help constructing a linq query that will return a list of usernames that show up the most in a log table for specific messages.
public class Log
{
public string Username {get; set;}
public string Message {get; set;}
}
I'm interested in rows where message is either "Created User", "Modified User", or "Deleted User".
So far I have:
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 the top 5 usernames based on the number or entries of these messages in the log table.
Use grouping to accomplish this task:
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);
精彩评论