Say I have a table Comments with these columns: Id, Comment, Category, CreatedDate, CommenterId
I want to get the top 5 categor开发者_如何转开发ies from the Comments table (based on the count of each category in that table). How can I do this in linq, to return either List or IQueryable?
You can use something like this:
var query = comments
.GroupBy(comment => comment.Category)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.Take(5);
Try something like this:
var topComments = from comment in Comments
group comment by comment.Category into grp
orderby grp.Count() descending
select grp.Key;
var topFive = topComments.Take(5);
精彩评论