如何从给定的父节点获取所有子节点? [英] How do I get all children from a given parent node?

查看:338
本文介绍了如何从给定的父节点获取所有子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of parent/child IDs and would like to get all child IDs for a given parent ID. There are no null parents (the top level IDs don't appear as child IDs).

当前,父母/孩子ID在列表中记录为KeyValuePair。如果会更好,可以很容易地将其更改为其他数据结构:

Currently the parent/child IDs are recorded as a KeyValuePair in a list, however this could be easily changed to another data structure if that would be better:

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

For example, here are sample parent/children. The children of parent 27 would be 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>> ,其中父级是键,值(整数列表)是子级?

Why dont you change the type of Dictionary<int, List<int>>, where the parent is the key and the value (list of ints) is the children?

然后,您会得到使用以下方法返回孩子列表:

Then you would get back the list of children using:

    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);
            }
        }
    }

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

You will need to weight out the performance impact as this will speed up reads and slow down writes (a huge majority of the time nobody would even notice).

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

You will also need to check if the list is in the dictionary using myitems.TryGet(...) and if not, you will need to create it, but this is o(1), so is practically instant.

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);
}

这篇关于如何从给定的父节点获取所有子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆