Click here to Skip to main content
14,266,228 members

Retrieving TreeView nodes as IEnumerable

Rate this:
4.89 (2 votes)
Please Sign up or sign in to vote.
4.89 (2 votes)
4 Feb 2012CPOL
By using a LinkedList, you can even mimic true recursive behavior without using recursive calls; the order will be "0,3,9,10,4,1,5,11,12,2,6,7,8", then:public static IEnumerable GetRecursive(this IEnumerable source, Func> subSelector){ var...

By using a LinkedList, you can even mimic true recursive behavior without using recursive calls; the order will be "0,3,9,10,4,1,5,11,12,2,6,7,8", then:


public static IEnumerable<T> GetRecursive<T>(this IEnumerable<T> source, 
                Func<T, IEnumerable<T>> subSelector)
{
    var list = new LinkedList<T>(source);
    try
    {
        LinkedListNode<T> current = list.First;
        while ( current != null )
        {
            yield return current.Value;
            
            IEnumerable<T> subs = subSelector(current.Value);
            if ( subs != null )
            {
                LinkedListNode<T> addPoint = current;
                foreach ( T subItem in subs )
                    addPoint = list.AddAfter(addPoint, subItem);
            }

            LinkedListNode<T> next = current.Next;
            list.Remove(current);
            current = next;
        }
    }
    finally
    {
        list.Clear();
    }
}

License

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

Share

About the Author

springy76
Web Developer
Germany Germany
No Biography provided

Comments and Discussions

 
GeneralReason for my vote of 4 LinkedList provides worse performanc... Pin
intrueder3-Feb-12 0:49
memberintrueder3-Feb-12 0:49 

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.

Alternative
Tip/Trick
Posted 30 Jan 2012

Tagged as

Stats

6.7K views