fork(1) download
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4.  
  5. public static class MyExtensions
  6. {
  7. public static IEnumerable<T> Traverse<T>(
  8. this IEnumerable<T> source,
  9. Func<T, IEnumerable<T>> fnRecurse)
  10. {
  11. if (source != null)
  12. {
  13. Stack<IEnumerator<T>> enumerators = new Stack<IEnumerator<T>>();
  14. try
  15. {
  16. enumerators.Push(source.GetEnumerator());
  17. while (enumerators.Count > 0)
  18. {
  19. var top = enumerators.Peek();
  20. while (top.MoveNext())
  21. {
  22. yield return top.Current;
  23.  
  24. var children = fnRecurse(top.Current);
  25. if (children != null)
  26. {
  27. top = children.GetEnumerator();
  28. enumerators.Push(top);
  29. }
  30. }
  31.  
  32. enumerators.Pop().Dispose();
  33. }
  34. }
  35. finally
  36. {
  37. while (enumerators.Count > 0)
  38. enumerators.Pop().Dispose();
  39. }
  40. }
  41. }
  42. }
  43.  
  44. public class Node
  45. {
  46. public int Id;
  47. public List<Node> Children;
  48. }
  49.  
  50. public class Test
  51. {
  52. public static void Main()
  53. {
  54. List<Node> nodes = new List<Node>()
  55. {
  56. new Node()
  57. {
  58. Id = 1,
  59. Children = new List<Node>()
  60. {
  61. new Node()
  62. {
  63. Id = 2,
  64. Children = new List<Node>()
  65. {
  66. new Node()
  67. {
  68. Id = 4
  69. },
  70. new Node()
  71. {
  72. Id = 5
  73. }
  74. }
  75. },
  76. new Node()
  77. {
  78. Id = 3
  79. }
  80. }
  81. }
  82. };
  83.  
  84. Console.WriteLine(String.Join(", ", nodes.Traverse(n => n.Children).Select(n => n.Id)));
  85. }
  86. }
Success #stdin #stdout 0.02s 18512KB
stdin
Standard input is empty
stdout
1, 2, 4, 5, 3