【问题标题】:How to use Linq to Group By individual items in a Collection?如何使用 Linq 对集合中的单个项目进行分组?
【发布时间】:2011-06-26 14:09:46
【问题描述】:

我正在尝试查找用于BlogPost 的最受欢迎的Tags

例如。

public class BlogPost
{
    public int Id { get; set; }
    public IEnumerable<string> Tags { get; set; }
}

所以我尝试了:

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

但这不会编译。错误是: Cannot implicitly convert type 'System.Linq.IQueryable&lt;{Tag: System.IEnumerable&lt;string&gt;, Count: int}&gt;' to 'System.Collections.Generic.Dictionary&lt;string, int&gt;'.

看看它是一个字符串列表吗?我希望浏览每篇博文中的每个标签,并计算出最受欢迎的标签。

【问题讨论】:

  • 您收到的错误来自您发布的代码之外。能否给出报错的代码?

标签: c# .net linq group-by


【解决方案1】:

我认为你不能在 IEnumerable&lt;string&gt; 上分组,试试这个:

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);

【讨论】:

    【解决方案2】:

    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);
    

    【讨论】:

      【解决方案3】:

      您希望对单个标签名称进行分组,而不是对整个标签列表进行分组,这正是您目前正在做的事情。试试这个:

      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);
      

      虽然这应该可以满足您的要求,但它不会修复您遇到的编译错误。那是别的地方。

      【讨论】:

        猜你喜欢
        • 2013-11-23
        • 1970-01-01
        • 1970-01-01
        • 2010-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多