Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.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/2/.net/20.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#_.net_Linq_Group By - Fatal编程技术网

C# 如何使用Linq按集合中的单个项进行分组?

C# 如何使用Linq按集合中的单个项进行分组?,c#,.net,linq,group-by,C#,.net,Linq,Group By,我试图找到最流行的标签,用于博客帖子 例如 但这并没有编译。错误是: 无法将类型“System.Linq.IQueryable”隐式转换为“System.Collections.Generic.Dictionary”。 看看这是一个字符串列表吗?我希望浏览每一篇博客文章中的每个标签,并数一数最受欢迎的标签。我认为你不能在IEnumerable上分组,请尝试以下方法: var tags = (from t in BlogPosts.SelectMany(p => p.Tags)

我试图找到最流行的
标签
,用于
博客帖子

例如

但这并没有编译。错误是:
无法将类型“System.Linq.IQueryable”隐式转换为“System.Collections.Generic.Dictionary”。


看看这是一个字符串列表吗?我希望浏览每一篇博客文章中的每个标签,并数一数最受欢迎的标签。

我认为你不能在
IEnumerable上分组,请尝试以下方法:

var tags = (from t in BlogPosts.SelectMany(p => p.Tags)
        group t by t into g
        select new {Tag = g.Key, Count = g.Count()})
    .OrderByDescending(o => o.Count)
    .Take(number);

SelectMany是这里的关键

  var tags = posts
     .SelectMany (p => p.Tags)
     .GroupBy (t => t).Select(t => new {Tag = t.First (), Count=t.Count ()})
     .OrderBy(tc => tc.Count)
     .Select(tc => tc.Tag)
     .Take (15);

您希望在单个标记名上分组,而不是在整个标记列表上分组,这是您当前正在做的事情。试试这个:

var tags =
    (from p in posts
    from tag in p.Tags
    group tag by tag into g
    select new {Tag = g.Key, Count = g.Count()})
.OrderByDescending(o => o.Count)
.Take(number);

尽管这应该满足您的要求,但它不会修复您遇到的编译错误。那是其他地方。

您收到的错误来自您发布的代码之外。你能告诉我报告错误的代码吗?
  var tags = posts
     .SelectMany (p => p.Tags)
     .GroupBy (t => t).Select(t => new {Tag = t.First (), Count=t.Count ()})
     .OrderBy(tc => tc.Count)
     .Select(tc => tc.Tag)
     .Take (15);
var tags =
    (from p in posts
    from tag in p.Tags
    group tag by tag into g
    select new {Tag = g.Key, Count = g.Count()})
.OrderByDescending(o => o.Count)
.Take(number);