Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Go to top

Retrieving TreeView nodes as IEnumerable

, 24 Jan 2012
Rate this:
Please Sign up or sign in to vote.
You can make this slightly more reusable by targeting the IEnumerable interface and providing a function to return the children of each item:public static class EnumerableExtensions{ private static IEnumerable DescendantsAndSelfIterator( IEnumerable source, ...
You can make this slightly more reusable by targeting the IEnumerable<T> interface and providing a function to return the children of each item:
 
public static class EnumerableExtensions
{
    private static IEnumerable<T> DescendantsAndSelfIterator<T>(
        IEnumerable<T> source, 
        Func<T, IEnumerable<T>> getChildren)
    {
        var queue = new Queue<IEnumerable<T>>();
        queue.Enqueue(source);
 
        while (0 != queue.Count)
        {
            foreach (var current in queue.Dequeue())
            {
                yield return current;
 
                var children = getChildren(current);
                if (null != children) queue.Enqueue(children);
            }
        }
    }
 
    public static IEnumerable<T> DescendantsAndSelf<T>(
        this IEnumerable<T> source, 
        Func<T, IEnumerable<T>> getChildren)
    {
        if (null == source) throw new ArgumentNullException("source");
        if (null == getChildren) return source;
        return DescendantsAndSelfIterator(source, getChildren);
    }
}
 
Your TreeView extension method then becomes:
public static class TreeViewExtension
{
    public static IEnumerable<TreeNode> AllTreeNodes(this TreeView treeView)
    {
        if (null == treeView) throw new ArgumentNullException("treeView");
 
        return treeView.Nodes.Cast<TreeNode>()
            .DescendantsAndSelf(n => n.Nodes.Cast<TreeNode>());
    }
}

License

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

Share

About the Author

Richard Deeming
Software Developer Nevalee Business Solutions
United Kingdom United Kingdom
No Biography provided
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralReason for my vote of 5 Your alternative is truly more reusa... PinmemberInTRUEdeR24-Jan-12 21:27 

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
Web02 | 2.8.140921.1 | Last Updated 24 Jan 2012
Article Copyright 2012 by Richard Deeming
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid