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
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.