Click here to Skip to main content
12,623,511 members (30,099 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

4.3K views
Posted

Retrieving TreeView nodes as IEnumerable

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

You may also be interested in...

Comments and Discussions

 
GeneralReason for my vote of 4 LinkedList provides worse performanc... Pin
InTRUEdeR3-Feb-12 1:49
memberInTRUEdeR3-Feb-12 1: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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161128.1 | Last Updated 4 Feb 2012
Article Copyright 2012 by springy76
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid