[英]How do I get all children from a given parent node?
我有一個父/子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));
例如,以下是示例父/子。 父母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, List<int>>
,其中父元素是鍵,值(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);
}
這很簡單。 只要認為你有以下數組中的列表
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.