c#groups子组foreach循环

时间:2016-02-22 19:59:32

标签: c# loops foreach

我知道这可能是一件简单的事情,但我试图遍历一个群组列表。如果该组有一个子组,我希望它再次为所有子组重复

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

组可以嵌套

在我的课堂上,我添加了List<GroupDevice> subgroup {get; set;}

在我的代码中,

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

但我只能降低一级。如何为每个子组等重复此方法......?

2 个答案:

答案 0 :(得分:2)

你可以使用递归来实现:

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

答案 1 :(得分:0)

递归才是答案。在我点击帖子的同时,我突然明白了。感谢

    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;