Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Retrieving TreeView nodes as IEnumerable

, 24 Jan 2012
Rate this:
Please Sign up or sign in to vote.
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

License

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

Share

About the Author

intrueder
Software Developer DevelopEx
Ukraine Ukraine
No Biography provided

Comments and Discussions

 
QuestionThoughts PinmemberPIEBALDconsult18-Jan-12 6:04 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140922.1 | Last Updated 24 Jan 2012
Article Copyright 2012 by intrueder
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid