如何使用Linq分组收集中的单个项目?

时间:2011-06-26 14:09:47

标签: c# .net linq group-by

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

例如

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<{Tag: System.IEnumerable<string>, Count: int}>' to 'System.Collections.Generic.Dictionary<string, int>'.

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

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:3)

我认为你不能在IEnumerable<string>上分组,试试这个:

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

答案 1 :(得分: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);

答案 2 :(得分:0)

您希望对单个标记名称进行分组,而不是对整个标记列表进行分组,这是您当前正在执行的操作。试试这个:

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

虽然这应该符合您的要求,但它不会解决您获得的编译错误。那是别的地方。