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

Retrieving TreeView nodes as IEnumerable

By , 24 Jan 2012
 

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)

About the Author

InTRUEdeR
Software Developer DevelopEx
Ukraine Ukraine
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionThoughtsmemberPIEBALDconsult18 Jan '12 - 6:04 

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 24 Jan 2012
Article Copyright 2012 by InTRUEdeR
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid