c# - 如何使用 Linq 对集合中的单个项目进行分组?

标签 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>'.

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

最佳答案

我不认为你可以在 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/

相关文章:

c# - 如何递归压缩文件夹?

.net - LINQ to Entities 无法识别该方法

c# - ConcurrentQueue ToList() 与 ToArray().ToList()

c# - 用 Linq 替换嵌套循环

c# - 获取 sql server 中最后插入的以 id 作为主键并且是一个标识的行

c# - 为 DLL 制作 .NET 包装器

java - Xamarin Java.Lang.Object 创建效率低下

c# - 链接图片源文件名与实际链接不同

c# - System.Security.Principal.WindowsIdentity 的这种使用是否合理安全?

c# - 如何在 C#/.NET 中从一个位图中减去另一个位图?