Group By with 3 nested objects

时间:2018-03-25 19:17:47

标签: c# linq

I was wondering how and what is the best way to perform 3 level hierarchy of GroupBy with Linq.

I have the following flat set of data (the list of data I get from an Excel workbook in which I read via LinqToExcel):

public string MasterPlanID { get; set; }

public string MasterPlanName { get; set; }

public string MasterPlanTypeID { get; set; }

public string MasterPlanTypeName { get; set; }

public int MasterPlanMinDuration { get; set; }

public int MasterPlanMaxDuration { get; set; }

public string SubjectID { get; set; }

public string SubjectName { get; set; }

public string ActivityID { get; set; }

public string ActivityName { get; set; }

public int ActivityDuration { get; set; }

public string ActivityTypeID { get; set; }

public string ActivityTypeName { get; set; }

Now, I need to have the following structure at the end:

MasterPlanID
MasterPlanName
MasterPlanTypeID
MasterPlanTypeName
MasterPlanMaxDuration
MasterPlanMinDuration
Subjects
     SubjectID
     SubjectName
         Activities
             ActivityID
             ActivityName
             And so on....

1 个答案:

答案 0 :(得分:1)

One MasterPlan can have multiple Subjects, One Subject can have multiple Activities, One Activity can have multiple ... and so on.

In code it will look like this:

var objects = /*your enumeration*/;
var masterPlans = objects
    .GroupBy(x => x.MasterPlanID)
    .Select(x => new
    {
        x.First().MasterPlanID,
        x.First().MasterPlanID,
        x.First().MasterPlanName,
        x.First().MasterPlanTypeID,
        x.First().MasterPlanTypeName,
        x.First().MasterPlanMaxDuration,
        x.First().MasterPlanMinDuration,
        Subjects = x
            .GroupBy(y => y.SubjectId)
            .Select(y => new
            {
                y.First().SubjectID,
                y.First().SubjectName,
                Activities = y
                    .GroupBy(z => z.ActivityID)
                    .Select(w => new 
                    {
                        w.First().ActivityID,
                        w.First().ActivityName
                    })
            })
    });

Variable masterPlans will contain a set of anonymous objects in desired hierarchy. It can be optimized by saving x.First() instead of calling it every time, but I think you will managae it by yourself.