gpt4 book ai didi

c# - 从父字段确定层次结构整数 C#

转载 作者:行者123 更新时间:2023-12-03 21:00:47 24 4
gpt4 key购买 nike

我需要确定显示树的层次结构级别,目前不需要链接关系,我有一个对象列表,如下所示:

public class ObjectData
{
public string ID;
public string hierarchyParent;
public int hierarchyLevel;
}

我需要根据其行级别设置 HierarchyLevel 整数。 HierarchyParent 变量包含其父级的 ID。我不知道每列有多宽,也不知道有多少行,因此它需要随着层次结构级别整数的升序或降序而动态变化。到目前为止,我已经能够确定第一行,但不确定如何继续,任何帮助将不胜感激!到目前为止:

List<ObjectData> Sort(List<ObjectData> objectToBeSorted){
List<ObjectData> returnlist = new List<ObjectData>();
string topObject = null;
foreach(ObjectData obj in objectToBeSorted)
{
if(obj.hierarchyParent == null){
topObject = obj.ID;
obj.hierarchyLevel = 1;
}
}
foreach(ObjectData obj in objectToBeSorted)
{
if(obj.hierarchyParent == topObject){

}
}



return returnlist;
}

最佳答案

这是示例数据和递归调用的快速尝试:

有用的部分是在AssignChild方法中。

public class ObjectData
{
public string ID;
public string hierarchyParent;
public int hierarchyLevel;
}

void Main()
{

var objects = new List<ObjectData>() {
new ObjectData() { ID = "Obj12", hierarchyParent = null },
new ObjectData() { ID = "Obj5", hierarchyParent = "Obj12" },
new ObjectData() { ID = "Obj9", hierarchyParent = "Obj12" },
new ObjectData() { ID = "Obj7", hierarchyParent = "Obj5" },
new ObjectData() { ID = "Obj99", hierarchyParent = "Obj58" },
new ObjectData() { ID = "Obj58", hierarchyParent = "Obj5" } };

ObjectData top = objects.Find(p => p.hierarchyParent == null);
top.hierarchyLevel = 1;

AssignChild(objects, top);

objects.Dump();
}

void AssignChild(List<ObjectData> all, ObjectData parent)
{
var child = all.FindAll(o => o.hierarchyParent == parent.ID);
child.ForEach(c => { c.hierarchyLevel = parent.hierarchyLevel +1; AssignChild(all, c); });
}

它可能可以优化,但应该可以工作。

关于c# - 从父字段确定层次结构整数 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41870070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com