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

标签 c# asp.net asp.net-mvc linq entity-framework

假设我有一个包含以下列的 Comments 表:Id、Comment、Category、CreatedDate、CommenterId

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

最佳答案

你可以这样使用:

var query = comments
    .GroupBy(comment => comment.Category)
    .OrderByDescending(g => g.Count())
    .Select(g => g.Key)
    .Take(5);

关于c# - 帮助 Linq 表达式根据字段计数返回字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4159866/

相关文章:

c# - 来自 bool 值的字符串

c# - 匹配 TestMethods 的正则表达式

c# - 回发后页面客户端验证问题

javascript - 如何为 id 的 @html.validation 赋值?

c# - 列出 View 中ViewBag的内容

c# - 带有 Win32 父窗口的 WPF OpenFileDialog;窗口在关闭时没有重新获得焦点

c# - 在 C# 中装箱值类型的用例?

asp.net - asmx 网络服务不读取 postdata

c# - 如何终止 session 或 session ID (ASP.NET/C#)

ASP.NET MVC。不知道如何使用 Url.action 将对象传递给 Controller