开发者

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

开发者 https://www.devze.com 2023-01-24 21:33 出处:网络
Say I have a table Comments with these columns: Id, Comment, Category, CreatedDate, CommenterId I want to get the top 5 categor开发者_如何转开发ies from the Comments table (based on the count of each

Say I have a table Comments with these columns: Id, Comment, Category, CreatedDate, CommenterId

I want to get the top 5 categor开发者_如何转开发ies from the Comments table (based on the count of each category in that table). How can I do this in linq, to return either List or 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消