如何从给定父节点获取所有子节点?

我有一个父/子ID列表,并希望获得给定父ID的所有子ID。 没有空父项(顶级ID不显示为子ID)。

目前,父/子ID在列表中记录为KeyValuePair,但是如果更好的话,可以很容易地将其更改为另一个数据结构:

List<KeyValuePair> groups = new List<KeyValuePair>(); groups.Add(new KeyValuePair(parentID, childID)); 

例如,以下是示例父/子。 父母27的孩子将是5944,2065,2066,2067,6248,6249,6250

 Parent Child 27 1888 1888 5943 1888 5944 5943 2064 5943 2065 5943 2066 5943 2067 2064 6248 2064 6249 2064 6250 

任何帮助将不胜感激!

为什么不更改Dictionary> ,其中父元素是键,值(int列表)是子元素?

然后你将使用以下命令返回子项列表:

  private List GetAllChildren(int parent) { List children = new List(); PopulateChildren(parent, children); return children; } private void PopulateChildren(int parent, List children) { List myChildren; if (myitems.TryGetValue(parent, out myChildren)) { children.AddRange(myChildren); foreach (int child in myChildren) { PopulateChildren(child, children); } } } 

您将需要权衡性能影响,因为这将加快读取速度并减慢写入速度(绝大多数时间没有人会注意到)。

您还需要使用myitems.TryGet(...)检查列表是否在字典中,如果没有,则需要创建它,但这是o(1),因此几乎是即时的。

 private static void AddEntry(int parent, int child) { List children; if (!myitems.TryGetValue(parent, out children)) { children = new List(); myitems[parent] = children; } children.Add(child); } 

这很简单。 只要认为你有以下数组中的列表

  List> groups = new List>(); groups.Add(new KeyValuePair(27, 1888)); groups.Add(new KeyValuePair(1888, 5943)); groups.Add(new KeyValuePair(1888, 5944)); groups.Add(new KeyValuePair(5943, 2064)); groups.Add(new KeyValuePair(5943, 2065)); groups.Add(new KeyValuePair(5943, 2066)); groups.Add(new KeyValuePair(5943, 2067)); groups.Add(new KeyValuePair(2064, 6248)); groups.Add(new KeyValuePair(2064, 6249)); groups.Add(new KeyValuePair(2064, 6250)); groups.Add(new KeyValuePair(2000, 1000)); // Pass the 1st parameter as the parent to get all children List childs = GetAllChild(27, groups); 

您需要使用“递归函数”来动态获取子项。 只需调用以下方法即可获取父级的所有子级

 public List GetAllChild(int id,List> newLst) { List list = new List(); for (int i = 0; i < newLst.Count; i++) { if (Convert.ToInt32(newLst[i].Key) == id) { if (!list.Contains(Convert.ToInt32(newLst[i].Value))) { list.Add(Convert.ToInt32(newLst[i].Value)); List l = GetAllChild(newLst[i].Value, newLst); list.AddRange(l); } } } return list; }