Get a list of all tree nodes (in all levels) in TreeView Controls

后端 未结 8 1672
故里飘歌
故里飘歌 2020-12-06 11:53

How can I get a list of all tree nodes (in all levels) in a TreeView control?

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 12:21

    I think my solution is more elegant, it uses generics (because TreeView can store each kind of objects derived from TreeNode) and has a single function recursively called. It should be straightforward also convert this as extension.

        List EnumerateAllTreeNodes(TreeView tree, T parentNode = null) where T : TreeNode
        {
            if (parentNode != null && parentNode.Nodes.Count == 0)
                return new List() { };
    
            TreeNodeCollection nodes = parentNode != null ? parentNode.Nodes : tree.Nodes;
            List childList = nodes.Cast().ToList();
    
            List result = new List(1024); //Preallocate space for children
            result.AddRange(childList); //Level first
    
            //Recursion on each child node
            childList.ForEach(n => result.AddRange(EnumerateAllTreeNodes(tree,n)));
    
            return result;
        }
    

    The usage is straightforward, just call:

        List allnodes = EnumerateAllTreeNodes(tree);
    

提交回复
热议问题