简化嵌套循环?

时间:2014-11-18 15:44:32

标签: c# loops recursion foreach

所以我用我的数据创建树结构,我想避免嵌套的嵌套嵌套重复。孩子们内部可能有儿童,我需要知道哪些数据可以折叠并提供文件夹图标。有没有办法简化这个?提前谢谢。

foreach (var i in mlist)
{
    // if this is a matching child
    if (i.key == dto.under.ToString())
    {
        // add this as a child
        i.children.Add(m1);
    }

    //check children also
    foreach (var i2 in i.children)
    {
        if (i2.key == dto.under.ToString())
        {
            // add this as a child
            i2.children.Add(m1);
        }

        if (i2.children.Count != 0)
        {
            i2.folder = true;
        }
        else
        {
            i2.folder = false;
        }


        foreach (var i3 in i2.children)
        {
            if (i3.key == dto.under.ToString())
            {
                // add this as a child
                i3.children.Add(m1);
            }

            if (i3.children.Count != 0)
            {
                i3.folder = true;
            }
            else
            {
                i3.folder = false;
            }

        }

    }


    if (i.children.Count != 0)
    {
        i.folder = true;
    }
    else
    {
        i.folder = false;
    }
}

2 个答案:

答案 0 :(得分:1)

这是您当前循环的递归示例

public void Traverse(List<Item> items, Item dto, Item m1)
{
    foreach (var i in items)
    {
        // if this is a matching child
        if (i.key == dto.under.ToString())
        {
            // add this as a child
            i.children.Add(m1);
        }
        i.folder = i.children.Count != 0;
        Traverse(i.children, dto, m1);
    }    
}
...
Traverse(mlist, dto, m1);

答案 1 :(得分:0)

你需要一个递归函数

foreach (var i in mlist)
{
    checkChildren(i);
}

然后

void checkChildren( List i ) // i is of type List?
{
    if (i.key == dto.under.ToString())
    {
        // add this as a child
        i.children.Add(m1);

        // what is m1? you may have to pass
        // this in as a parameter. I am not
        // really sure what it is
    }

    if (i.children.Count != 0)
    {
        i.folder = true;
    }
    else
    {
        i.folder = false;
    }

    foreach (var i2 in i.children)
    {
        checkChildren(i2);
        // this will call the same function again,
        // but this time on the next level of your hierarchy
    }

}