简体   繁体   English

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

[英]Help with Linq expression to return a list of strings based on field count

Say I have a table Comments with these columns: Id, Comment, Category, CreatedDate, CommenterId 说我有一个表与这些列的评论:Id,Comment,Category,CreatedDate,CommenterId

I want to get the top 5 categories from the Comments table (based on the count of each category in that table). 我想从评论表中获取前5个类别(基于该表中每个类别的计数)。 How can I do this in linq, to return either List or IQueryable? 我如何在linq中执行此操作,以返回List或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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM