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