以递归方式读取所有节点和子节点

本文关键字:节点 子节点 递归 方式 读取 | 更新日期: 2023-09-27 18:32:22

我有一个带有节点的对象节点。我想读取所有节点和子节点,并将它们显示在 asp.net 下拉列表控件中。

节点的类型为 :

Microsoft.TeamFoundataion.WorkItemTracking.Client.Node

类节点如下所示:

public class Node
{
    public string Name { get; set; }
    public string Path { get; set; }
}
每个节点都有许多子节点,子节点

有更多的子节点,依此类推。

我编写了代码来获取节点和子节点的第一级。我想不出如何递归读取所有节点?

Dictionary<string,string> ParentN = new Dictionary<string,string>();
Dictionary<string, string> childN = new Dictionary<string, string>();
foreach (Node area in Proj.Nodes)
{
    ParentN.Add(area.Name, area.Path);
    Console.WriteLine(area.Path);
    foreach (Node item in area.ChildNodes)
    {
        childN.Add(item.Name, item.Path);
        Console.WriteLine(item.Path);
    }
}

以递归方式读取所有节点和子节点

为此需要一个递归函数。孩子也可以是父母。如果一个孩子下面没有孩子,那么我们不会把它添加到父母的字典中。

void GetNode(Node parent)
{
    if (parent.ChildNodes.Any())
    {
        ParentN.Add(parent.Name, parent.Path);
        foreach(child in parent.ChildNodes)
        {
            childN.Add(child.Name, child.Path);
            GetNode(child);
        }
    }
    Console.WriteLine(parent.Name);
}

您发布的类节点不包含子节点。我假设你的意思是:

public class Node
{
    public string Name { get; set; }
    public string Path {get; set;}
    IList<Node> ChildNodes { get; set; }
}

您可以按以下方式执行此操作:

static class NodeExtensions
{
    public static IEnumerable<Node> ReadChildNodes(this Node node)
    {
        foreach(Node childNode in node.ChildNodes){
            if(childNode.ChildNodes != null && childNode.ChildNodes.Any()){
                foreach(Node grandChildren in childNode.ReadChildNodes())
                    yield return grandChildren;
            }
            yield return childNode;
        }
    }
}

可能这段代码可以改进,但它有效,我想......