【问题标题】:Simplify nested loops?简化嵌套循环?
【发布时间】:2015-01-15 20:54:34
【问题描述】:

所以我正在用我的数据创建一个树结构,并且我想避免嵌套嵌套的嵌套重复。孩子中的孩子中可能有孩子,我需要知道哪些数据可以折叠并给出一个文件夹图标。有没有办法简化这个?提前致谢。

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

【问题讨论】:

  • 制作循环recursive
  • 你的if语句可以简单的写成i.folder = i.children.Count != 0
  • 这和 Javascript 有什么关系?

标签: c# loops recursion foreach


【解决方案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);

【讨论】:

    【解决方案2】:

    你需要一个递归函数

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-23
      • 2019-12-28
      • 2022-12-07
      相关资源
      最近更新 更多