LINQ嵌套集合

时间:2012-01-28 23:33:31

标签: c# linq

我有一个有子集合的类。像这样:

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

这将返回如下内容:

{type1,13} {type2,26}

等等。

但我怎么能按Subitem算?

返回类似的内容: {subitem1,15} {subitem2,46}

1 个答案:

答案 0 :(得分:2)

您的代码示例不合法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());