在linq to sql中,我可以在一个组中选择(和分组)吗?

时间:2013-10-05 23:08:51

标签: c# .net linq linq-to-sql

我有以下课程:

class XXX
{
    int XXXType{get;set;}
    List<YYY> Children{get;set;}
}
class YYY
{
    int YYYType{get;set;}
}

我想找到属性XXXType具有相同值的项目数,并且对于每个组,我想查找其子项具有属性YYYType的相同值的项目数。 linq to sql是否支持select / group中的select / group?我没有得到任何编译/运行时异常,但YYYChildren的长度始终为零。

(from x in XXX).GroupBy(x=>x.XXXType, (key, values) => new {
    XXXType = key,
    Count = values.Count(),
    YYYChildren = (from y in values.SelectMany(z=>z.Children).GroupBy(y=>y.YYYType, (key, values) =>
        new {
             YYYType = key,
             Count = values.Count()
        }
    });

1 个答案:

答案 0 :(得分:0)

像这样......

//示例数据

   var xxxList = new List<XXX> {
            new XXX()
            {
                XXXType = 1,
                Children = new List<YYY>() {
                        new YYY() {YYYType = 1},
                        new YYY() {YYYType = 1},
                        new YYY() {YYYType = 2},
                        new YYY() {YYYType = 2}
                    }
            }
        };

//查询:

        foreach(var x in xxxList.GroupBy(info => info.XXXType)
                    .Select(group => new { 
                         key = group.Key, 
                         Count = group.Count(),
                         YYYChildren = (from y in xxxList.SelectMany(z=>z.Children).GroupBy(y=>y.YYYType, (key, values) =>
                                        new {
                                             YYYType = key,
                                             Count = values.Count()
                                        }) select y.YYYType)
                    }))
        {
             Console.WriteLine("XXXType :{0}, Number Of XXXTypes :{1}, Number Of YYYChildren :{2}", x.key, x.Count, x.YYYChildren.Count());
        }

结果: XXXType:1,XXXTypes数量:1,YYYChildren数量:2