我有一个父/子 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>>
,其中父级是键,值(整数列表)是子级?
然后你可以使用以下命令取回孩子的列表:
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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)