Click here to Skip to main content
15,886,110 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

Retrieving TreeView nodes as IEnumerable

Rate me:
Please Sign up or sign in to vote.
4.75/5 (4 votes)
24 Jan 2012CPOL 48.9K   9   3
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)


Written By
Software Developer DevelopEx
Ukraine Ukraine
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionExcelente Pin
PiherVelascoGarcia9-Oct-16 17:45
professionalPiherVelascoGarcia9-Oct-16 17:45 
QuestionThoughts Pin
PIEBALDconsult18-Jan-12 6:04
mvePIEBALDconsult18-Jan-12 6:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.