Accessing all the nodes in TreeView Control

前端 未结 7 1608
小蘑菇
小蘑菇 2020-11-27 22:27

I have a TreeView Control with set of nodes and child nodes. For example:

ROOT has A,B,C.

A has a1, a2, a3 and then

7条回答
  •  情书的邮戳
    2020-11-27 22:51

    You can create an Extension Method that returns a List.

    Descendants Extension Method

    using System.Linq;
    using System.Windows.Forms;
    using System.Collections.Generic;
    
    public static class Extensions
    {
        public static List Descendants(this TreeView tree)
        {
            var nodes = tree.Nodes.Cast();
            return nodes.SelectMany(x => x.Descendants()).Concat(nodes).ToList();
        }
    
        public static List Descendants(this TreeNode node)
        {
            var nodes = node.Nodes.Cast().ToList();
            return nodes.SelectMany(x => Descendants(x)).Concat(nodes).ToList();
        }
    }
    

    To get all nodes of a TreeView

    var nodes = this.treeView1.Descendants();
    

    To get all child nodes of a Node

    var nodes = this.treeView1.Nodes[0].Descendants();
    

    You can also use linq to search between nodes.

    Ancestors Extension Method

    To get ancestors of a node, you may also me interested to Ancestors extension methods.

提交回复
热议问题