using System; using System.Linq; using System.Collections.Generic; public static class MyExtensions { public static IEnumerable Traverse( this IEnumerable source, Func> fnRecurse) { if (source != null) { Stack> enumerators = new Stack>(); try { enumerators.Push(source.GetEnumerator()); while (enumerators.Count > 0) { var top = enumerators.Peek(); while (top.MoveNext()) { yield return top.Current; var children = fnRecurse(top.Current); if (children != null) { top = children.GetEnumerator(); enumerators.Push(top); } } enumerators.Pop().Dispose(); } } finally { while (enumerators.Count > 0) enumerators.Pop().Dispose(); } } } } public class Node { public int Id; public List Children; } public class Test { public static void Main() { List nodes = new List() { new Node() { Id = 1, Children = new List() { new Node() { Id = 2, Children = new List() { new Node() { Id = 4 }, new Node() { Id = 5 } } }, new Node() { Id = 3 } } } }; Console.WriteLine(String.Join(", ", nodes.Traverse(n => n.Children).Select(n => n.Id))); } }