Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 帮助使用Linq表达式返回基于字段计数的字符串列表_C#_Asp.net_Asp.net Mvc_Linq_Entity Framework - Fatal编程技术网

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

C# 帮助使用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()) .

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


我想从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。工作得很有魅力。