我试图创建一个树状结构。每个班级都有一个父级字段和子级列表,与父级班级是同一班级。基本的东西。C# - 基于深度值和列表索引创建树状结构
这里是我正在使用的类的基本版本。
public class TreeElement {
public string name;
public int depth;
public int id;
public TreeElement parent;
public List<TreeElement> children = new List<TreeElement>();
}
现在,当我得到初始数据时,我将所有这些类都列入列表中。我的树视图中的每个项目都在一个大列表中,我可以继续进行的是项目的深度值和索引。因此,该列表将基本上是这个样子:
(0) -1
(1) |- 0
(2) |-- 1
(3) |-- 1
(4) | |-- 2
(5) |-- 1
(x)表示在列表中的索引。其余的数字是深度值。
现在我的实际问题。我很难根据这些值制作我自己的列表,而且我基本上只知道每个孩子的单个项目被添加到哪里并且兄弟姐妹会被忽略。我真的找不到将这些考虑在内的方法。
这里是我到目前为止的代码(这可能是这个可怕的错误):
private List<TreeElement> GenerateTreeStructure(List<TreeElement> baseList)
{
// Base list is the list I get provided with.
List<TreeElement> newList = new List<TreeElement>();
TreeElement root = null;
TreeElement previousFolder = null;
int previousdepth = -99;
for (int i = 0; i < baseList.Count; i++)
{
TreeElement currentResource = baseList[i];
if (currentResource.depth == -1 && ShowRootFolder) // The root folder.
{
root = currentResource;
// (Name, depth, parent)
newList.Add(new TreeElement("Root", currentResource.depth, null));
previousFolder = root;
previousdepth = root.depth;
}
else if (!ShowRootFolder && currentResource.depth <= 0)
{
// If root folder is not shown, take all the children of the root folder instead.
if (currentResource.depth != -1)
{
previousFolder = new TreeElement(currentResource.name, currentResource.depth, null);
previousdepth = previousFolder.depth;
newList.Add(previousFolder);
}
}
else
{
if (currentResource.depth > previousdepth)
{
TreeElement newResource = new TreeElement(currentResource.name, currentResource.depth, null);
previousFolder.children.Add(newResource);
previousdepth = currentResource.depth;
previousFolder = newResource;
}
}
}
return newList;
}
我希望解释我的问题。我一直坚持这一段时间,我希望能得到一些帮助!
谢谢
这正是我想要的,谢谢!并澄清我为什么返回一个列表:我需要输入一个列表到树视图显示。但我只是简单地将它转换成使用你的代码返回一个列表。 – Hertzole