Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Retrieving TreeView nodes as IEnumerable

4.75/5 (4 votes)
24 Jan 2012CPOL 49.4K  
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.


C#
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:


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

or in LINQ expressions:


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

The result of the last code example is:


Result

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)