C# 简化嵌套循环?
所以我用我的数据创建一个树结构,我想避免嵌套重复。在children和children中可以有children,我需要知道哪些数据可以折叠,并给出一个文件夹图标。有没有办法简化这一点?提前谢谢C# 简化嵌套循环?,c#,loops,recursion,foreach,C#,Loops,Recursion,Foreach,所以我用我的数据创建一个树结构,我想避免嵌套重复。在children和children中可以有children,我需要知道哪些数据可以折叠,并给出一个文件夹图标。有没有办法简化这一点?提前谢谢 foreach (var i in mlist) { // if this is a matching child if (i.key == dto.under.ToString()) { // add this as a child i.child
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;
}
}
你需要一个递归函数
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
}
}
下面是当前循环的递归示例
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);
public void遍历(列表项目、项目dto、项目m1)
{
foreach(项目中的var i)
{
//如果这是匹配的子项
if(i.key==dto.under.ToString())
{
//将此作为子项添加
i、 儿童。加上(m1);
}
i、 folder=i.children.Count!=0;
遍历(即子对象、dto、m1);
}
}
...
导线测量(mlist、dto、m1);
进行循环。您的if语句可以简单地写成i.folder=i.children.Count!=0
这与Javascript有什么关系?