65.9K
CodeProject is changing. Read more.
Home

Retrieving TreeView nodes as IEnumerable

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.89/5 (2 votes)

Jan 30, 2012

CPOL
viewsIcon

8771

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();
    }
}