65.9K
CodeProject is changing. Read more.
Home

Retrieving TreeView nodes as IEnumerable

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (4 votes)

Jan 18, 2012

CPOL
viewsIcon

49454

Extension method to make it easy to retrieve all nodes of a TreeView control.

To retrieve all nodes from a TreeView control, the recursion method is normally used. But I prefer to use a Queue, implementing the BFS algorithm. I want to propose a simple extension method that provides you with an easy way to retrieve all nodes from a TreeView without recursion, as a simple IEnumerable.

public static class TreeViewExtension
{
    public static IEnumerable<TreeNode> AllTreeNodes(this TreeView treeView)
    {
        Queue<TreeNode> nodes = new Queue<TreeNode>();
        foreach (TreeNode item in treeView.Nodes)
            nodes.Enqueue(item);

        while (nodes.Count > 0)
        {
            TreeNode node = nodes.Dequeue();
            yield return node;
            foreach (TreeNode item in node.Nodes)
                nodes.Enqueue(item);
        }
    }
}

You can use this code as follows:

foreach(var node in treeView1.AllTreeNodes())
{
...
}

or in LINQ expressions:

treeView1
.AllTreeNodes()
.Aggregate<TreeNode, String>("", (s, n) => s + n.Name + Environment.NewLine);

The result of the last code example is:

Result