C# 帮助使用Linq表达式返回基于字段计数的字符串列表
假设我有一个带有以下列的表注释:Id、Comment、Category、CreatedDate、CommenterIdC# 帮助使用Linq表达式返回基于字段计数的字符串列表,c#,asp.net,asp.net-mvc,linq,entity-framework,C#,Asp.net,Asp.net Mvc,Linq,Entity Framework,假设我有一个带有以下列的表注释:Id、Comment、Category、CreatedDate、CommenterId 我想从Comments表中获得前5个类别(基于该表中每个类别的计数)。如何在linq中执行此操作,以返回列表或IQueryable?您可以使用以下内容: var query = comments .GroupBy(comment => comment.Category) .OrderByDescending(g => g.Count()) .
我想从Comments表中获得前5个类别(基于该表中每个类别的计数)。如何在linq中执行此操作,以返回列表或IQueryable?您可以使用以下内容:
var query = comments
.GroupBy(comment => comment.Category)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.Take(5);
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);
试着这样做:
var query = comments
.GroupBy(comment => comment.Category)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.Take(5);
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。工作得很有魅力。