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

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

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

8条回答
  •  -上瘾入骨i
    2020-12-06 12:27

    Lazy LINQ approach, just in case you're looking for something like this:

    private void EnumerateAllNodes()
    {
        TreeView myTree = ...;
    
        var allNodes = myTree.Nodes
            .Cast()
            .SelectMany(GetNodeBranch);
    
        foreach (var treeNode in allNodes)
        {
            // Do something
        }
    }
    
    private IEnumerable GetNodeBranch(TreeNode node)
    {
        yield return node;
    
        foreach (TreeNode child in node.Nodes)
            foreach (var childChild in GetNodeBranch(child))
                yield return childChild;
    }
    

提交回复
热议问题