【问题标题】:Help with Linq expression to return a list of strings based on field count帮助 Linq 表达式根据字段计数返回字符串列表
【发布时间】:2010-11-11 22:23:41
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    你可以这样使用:

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

    【讨论】:

      【解决方案2】:

      试试这样的:

      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);
      

      【讨论】:

      • 感谢@scmccart 和@Mark Byers。像魅力一样工作。
      猜你喜欢
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多