我试图找到最受欢迎的 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>'.
看到它是一个字符串列表了吗?我希望浏览每篇博文中的每个标签,并计算出最受欢迎的标签。
最佳答案
我不认为你可以在 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);
关于c# - 如何使用 Linq 对集合中的单个项目进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6484464/