代码之家  ›  专栏  ›  技术社区  ›  Prabhu

帮助使用Linq表达式返回基于字段计数的字符串列表

  •  3
  • Prabhu  · 技术社区  · 15 年前

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

    我想从Comments表中获得前5个类别(基于该表中每个类别的计数)。我怎样才能在linq中这样做,返回List或IQueryable?

    2 回复  |  直到 15 年前
        1
  •  4
  •   scmccart    15 年前

    试试这样的:

    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);
    
        2
  •  6
  •   Mark Byers    15 年前

    你可以用这样的东西:

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