【发布时间】:2021-08-25 16:25:42
【问题描述】:
我正在尝试使用递归重构一些代码以扩展可能性(并清理代码)。
问题来了:
我有一个看起来像文件夹结构的 Treeview 对象:
- ElementA
- ElementB
- Element B1
- Element B2
- Element B2-1
- Element B3
- Element B3-1
- Element B3-1-1
- Element C
This is the guilty class:
public class TreeNode
{
private readonly string name; //Name of the node
private readonly string path; //Path of the node \\foo\\foo\\bar
public List<TreeNode> children; //list of TreeNode children
public void Add(TreeNode tName) //Add a child to a specific node
{
if (this.children is null)
this.children = new List<TreeNode>();
this.children.Add(tName);
}
}
我必须根据从后端获取的文件夹列表创建一个 TreeNode 列表。
现在我的代码:
List<TreeNode> nList = new List<TreeNode>(); // The list I want to fill in
ICollection<CfgFolder> folders= new List<CfgFolder>(); //Collection of folder to base myself on
//here get CfgFolder list from backend
//...
//
foreach (var folder in folders)
{
TreeNode newRow = new TreeNode(folder.Name, folder.ObjectPath); //Create a TreeNode without children (this is the new object to add)
bool added = false;
if (nList.Count == 0) // Add first element
nList.Add(new TreeNode(folder.Name, folder.ObjectPath));
else
{
foreach (var child in nList.ToList())
{
if (child.Path == newRow.Path) // If first level add simply to the list (same initial path \\Root )
{
nList.Add(new TreeNode(folder.Name, folder.ObjectPath));
added = true;
break;
}
}
if (!added)
{
foreach (var child in nList.ToList())
{
if (child.Path + "\\" + child.Name == newRow.Path) // If second level add to a child (path like \\ROOT\\Folder )
{
nList.FirstOrDefault(x => x.Name == child.Name).Add(new TreeNode(folder.Name, folder.ObjectPath));
added = true;
break;
}
}
}
if (!added)
{
foreach (var child in nList.ToList())
{
foreach (var child2 in child.children)
{
if (child2.Path + "\\" + child2.Name == newRow.Path) // If third level add to a child of the child (path like \\ROOT\\Folder\\SubFolder )
{
nList.FirstOrDefault(x => x.Name == child.Name).children.FirstOrDefault(x => x.Name == child2.Name).Add(new TreeNode(folder.Name, folder.ObjectPath));
added = true;
break;
}
}
}
}
//Also 4th level, ... till n level
}
}
这工作正常,我可以获得想要的结构,但这并不好看,我正在努力创建返回我的 nList 正确更新的递归方法。
这看起来像这样,但是当我在每个递归调用上重写“Mylist”时,这并不好:-(
无论如何,我能够找到添加文件夹的正确位置,但无法正确更新初始 nList。
private List<TreeNode> Recursive(List<TreeNode> Mylist, TreeNode newRow, bool added, int? loop = 0)
{
if (!added)
{
foreach (var child in Mylist.ToList())
{
if (child.Path + "\\" + child.Name == newRow.Path)
{
Mylist.FirstOrDefault(x => x.Name == child.Name).Add(new TreeNode(newRow.Name, newRow.ObjectPath)); //This line is false it should be something like nList[Mylist.Position]
added = true;
break;
}
}
}
if (added)
return Mylist; //This line is false also
return Recursive(Mylist[loop??0].children.ToList(), newRow, added, path,loop+1);
}
我希望我的解释是可以理解的。
【问题讨论】: