0

I know this may be a simple thing, but I am trying to loop through a list of groups. If the group has a subgroup I want it to repeat again for all subgroups

group1<br>
subgroup1<br>
   Device1<br>
   Device2<br>
group2<br>
 subgroup1<br>
  subsubgroup1<br>
   Device3<br>
 subgroup2<br>
   Device4<br>

groups can be nested

In my class, I have added a List<GroupDevice> subgroup {get; set;}

in my code,

public void getgrouptree()
{
    List<DeviceGroup> rootgroup = db.DeviceGroups
                                    .Where(a => a.ParentGroupID == 0)
                                    .ToList();

    foreach (var item in rootgroup)
    {
        int count = db.DeviceGroups
                      .Where(a => a.ParentGroupID == item.GroupID)
                      .Count();
        if (count >= 1)
        {
            item.SubGroup = db.DeviceGroups
                              .Where(a => a.ParentGroupID == item.GroupID)
                              .ToList();
        }
    }

    return;
}

But I can only go one level down. How do I repeat this method for each subgroup etc...?

D Stanley
  • 149,601
  • 11
  • 178
  • 240
Jeremy Hobbs
  • 181
  • 3
  • 7

2 Answers2

2

You can do it using recursion:

public void GetGroupTree()
{
    List<DeviceGroup> rootgroup = db.DeviceGroups.Where(a => a.ParentGroupID == 0).ToList();

    foreach (var item in rootgroup)
        GetGroupTree(item);
}

public void GetGroupTree(DeviceGroup group)
{
    var subGroups = db.DeviceGroups.Where(a => a.ParentGroupID == group.GroupID).ToList();

    if (subGroups.Count > 0)
    {
        group.SubGroup = subGroups;
        foreach (var item in group.SubGroup)
            GetGroupTree(item);
    }
}
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
0

Recursion was the answer. It dawned on me about the same time I clicked post. Thanks

    public ActionResult getgrouptree()
    {
        List<DeviceGroup> rootgroup = db.DeviceGroups.Where(a => a.ParentGroupID == 0).ToList();

        foreach (var item in rootgroup)
        {
            item.SubGroup = devicesubgroup(item);

        }

        return View(rootgroup);
    }
    public List<DeviceGroup> devicesubgroup(DeviceGroup subgroup1)
    {
        List<DeviceGroup> subgroup = new List<DeviceGroup>();
        int count = db.DeviceGroups.Where(a => a.ParentGroupID == subgroup1.GroupID).Count();
        if (count >= 1)
        {
            subgroup = subgroup1.SubGroup = db.DeviceGroups.Where(a => a.ParentGroupID == subgroup1.GroupID).ToList();
            foreach (var item in subgroup)
            {
                devicesubgroup(item);
            }
        }
        return subgroup;
Jeremy Hobbs
  • 181
  • 3
  • 7