Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Retrieving TreeView nodes as IEnumerable

4.89/5 (2 votes)
4 Feb 2012CPOL 8.8K  
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:


C#
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)