Linq GroupBy Clause

时间:2015-03-17 04:00:10

标签: c# asp.net asp.net-mvc linq

var result = rows.GroupBy(x => new { y = x["AcademicYearId"] })
    .Select(
        g => new
        {
            AcademicYearId = g.Key.y,
            ClassGroups = g.GroupBy(x => new { y = x["ClassName"], h = x["ClassGroupId"], i = x["ClassYearId"] })
            .Select(
                classYear => new
                {
                    ClassName = classYear.Key.y,
                    ClassGroupId = classYear.Key.h,
                    ClassYearId=classYear.Key.i,
                    ClassDivisions = classYear.GroupBy(x => new { b = x["Division"], a = x["DivisionId"] })
                    .Select(
                    clsDiv => new
                    {
                        DivisionId = clsDiv.Key.a,
                        Division = clsDiv.Key.b                               
                    })
                })
        });

这是工作代码,但我希望“ClassDivisions”作为orderBy Division。我该怎么做?

1 个答案:

答案 0 :(得分:0)

这是你想要的吗?

var result =
    rows
        .GroupBy(x => new { y = x["AcademicYearId"] })
        .Select(g => new
        {
            AcademicYearId = g.Key.y,
            ClassGroups =
                g
                    .GroupBy(x => new { y = x["ClassName"], h = x["ClassGroupId"], i = x["ClassYearId"] })
                    .Select(classYear => new
                    {
                        ClassName = classYear.Key.y,
                        ClassGroupId = classYear.Key.h,
                        ClassYearId=classYear.Key.i,
                        ClassDivisions =
                            classYear
                                .GroupBy(x => new { b = x["Division"], a = x["DivisionId"] })
                                .Select(clsDiv => new
                                {
                                    DivisionId = clsDiv.Key.a,
                                    Division = clsDiv.Key.b                               
                                })
                                .OrderBy(clsDiv => clsDiv.Division)
                    })
        });