c#获取TreeView父节点列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/560628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:12:12  来源:igfitidea点击:

c# Obtain a list of TreeView Parent nodes

c#winformstreeviewparent-node

提问by TK.

If I have a TreeView (myTreeview),how can I obtain a list of all the nodes that are parent nodes? i.e. nodes that have children

如果我有一个 TreeView (myTreeview),我如何获得所有作为父节点的节点的列表?即有孩子的节点

采纳答案by ng5000

myTreeview.Nodes will give you a list of root nodes as defined by MS which basically means nodes on the root branch of the tree.

myTreeview.Nodes 会给你一个由 MS 定义的根节点列表,这基本上意味着树的根分支上的节点。

This code will build a list of root nodes with children:

此代码将构建一个包含子节点的根节点列表:

    IList<TreeNode> nodesWithChildren = new List<TreeNode>();
    foreach( TreeNode node in myTreeview.Nodes )
        if( node.Nodes.Count > 0 ) nodesWithChildren.Add( node );


Update: and if you wanted all nodes in the TreeView that had a child regardless of how deep into the tree then use a bit of recursion, e.g.

更新:如果你想要 TreeView 中有一个孩子的所有节点,不管树有多深,那么使用一点递归,例如

private static IList<TreeNode> BuildParentNodeList(TreeView treeView)
{
    IList<TreeNode> nodesWithChildren = new List<TreeNode>();

    foreach( TreeNode node in treeView.Nodes  )
        AddParentNodes(nodesWithChildren, node);

    return nodesWithChildren;
}

private static void AddParentNodes(IList<TreeNode> nodesWithChildren, TreeNode parentNode)
{
    if (parentNode.Nodes.Count > 0)
    {
        nodesWithChildren.Add( parentNode );
        foreach( TreeNode node in parentNode.Nodes )
            AddParentNodes( nodesWithChildren, node );
    }
}


Update 2: Recursion method with only 1 foreach loop:

更新 2:只有 1 个 foreach 循环的递归方法:

private static IList<TreeNode> BuildParentNodeList(TreeView treeView)
{
    IList<TreeNode> nodesWithChildren = new List<TreeNode>();
    AddParentNodes( nodesWithChildren, treeView.Nodes );
    return nodesWithChildren;
}

private static void AddParentNodes(IList<TreeNode> nodesWithChildren, TreeNodeCollection parentNodes )
{
    foreach (TreeNode node in parentNodes)
    {
        if (node.Nodes.Count > 0)
        {
            nodesWithChildren.Add( node );
            AddParentNodes(nodesWithChildren, node.Nodes);
        }
    }
}

回答by user17541

private void AddNonLeafNodes(List<TreeNode> nonLeafNodes, TreeNodeCollection nodes)
{
    foreach( TreeNode node in nodes )
    {
        if( node.Nodes.Count > 0 )
        {
            nonLeafNodes.Add(node);
            AddNonLeafNodes(nonLeafNodes,node.Nodes);
        }
    }
}

List<TreeNode> nonLeafNodes = new List<TreeNode>();
AddNonLeafNodes(nonLeafNodes,treeView1.Nodes);