LINQ嵌套集合

本文关键字:集合 嵌套 LINQ | 更新日期: 2023-09-27 18:21:58

我有一个类,它有一个子集合。类似这样的东西:

public class Item { 
    public string Type {get;set}
    public Subitem[] {get;set;}
}

我知道我可以通过这种方式分类和计数:

var count = (from x in items
            group x by x.Type into grouped
            select new {
                typename = grouped.Key,
                count = grouped.Count()
                }).ToDictionary<string, int>(x => x.typename, x => x.count);

这将返回如下内容:

{类型1,13}{类型2,26}

等等

但是我怎样才能按分项计数呢?

返回如下内容:{子项1,15}{子项2,46}

LINQ嵌套集合

您的代码示例不是合法的C#,但假设您的项目中有一个名为Subitems的集合,则可以使用SelectMany()或查询语法:

var count = (from i in items
             from x in i.Subitems
             group x by x into grouped
             select new 
             {
                typename = grouped.Key,
                count = grouped.Count()
              }).ToDictionary(x => x.typename, x => x.count);

或者在方法语法中:

var countDict = items.SelectMany(x => x.Subitem)
                     .GroupBy(x => x)
                     .ToDictionary(g => g.Key, g => g.Count());