帮助Linq表达式根据字段计数返回字符串列表

Pra*_*bhu 3 c# linq asp.net asp.net-mvc entity-framework

说我有一个表与这些列的评论:Id,Comment,Category,CreatedDate,CommenterId

我想从评论表中获取前5个类别(基于该表中每个类别的计数).我如何在linq中执行此操作,以返回List或IQueryable?

Mar*_*ers 6

你可以使用这样的东西:

var query = comments
    .GroupBy(comment => comment.Category)
    .OrderByDescending(g => g.Count())
    .Select(g => g.Key)
    .Take(5);
Run Code Online (Sandbox Code Playgroud)