2012-06-26 138 views
4

我有一个父/子ID的列表,并希望获得给定父ID的所有子ID。没有空父母(顶级ID不显示为子ID)。如何从给定父节点获取所有孩子?

目前的父/子ID被记录在列表中的KeyValuePair,但是这可以很容易地改变为另一种数据结构,如果他们会更好:

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

例如,这里有样品父/儿童。父母的孩子将是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 

任何帮助将不胜感激!

+1

您尝试了哪些方法,哪些方法无效?走在树上是非常标准的任务......所以目前有什么问题还不清楚。 –

回答

5

为什么不更改Dictionary<int, List<int>>的类型,其中父项是关键字,值(整数列表)是儿童?

,那么你会使用找回孩子的名单:

private List<int> GetAllChildren(int parent) 
    { 
     List<int> children = new List<int>(); 
     PopulateChildren(parent, children); 
     return children; 
    } 

    private void PopulateChildren(int parent, List<int> children) 
    { 
     List<int> 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<int> children; 
    if (!myitems.TryGetValue(parent, out children)) 
    { 
     children = new List<int>(); 
     myitems[parent] = children; 
    } 
    children.Add(child); 
} 
+0

虽然这并不能帮助我找到所有的孩子 - 它只会得到一个级别的孩子。 – Marcus

+0

好的,所以你想递归获得所有的孩子? – Blueberry

+0

是的,谢谢! – Marcus

0

它很简单。只是认为你有以下列表中的列表

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

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

public List<int> GetAllChild(int id,List<KeyValuePair<int, int>> newLst) 
{ 
     List<int> list = new List<int>(); 
     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<int> l = GetAllChild(newLst[i].Value, newLst); 
        list.AddRange(l); 
       } 
      } 
     } 
     return list; 
} 
相关问题