forked from BotBuilderCommunity/botbuilder-community-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EnumerableExtensions.cs
51 lines (46 loc) · 1.55 KB
/
EnumerableExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using System.Text;
namespace Bot.Builder.Community.Dialogs.ChoiceFlow.Extensions
{
public static class EnumerableExtensions
{
public static IEnumerable<T> SelectRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> getChildren)
{
if (null == source) throw new ArgumentNullException("source");
if (null == getChildren) return source;
return SelectRecursiveIterator(source, getChildren);
}
private static IEnumerable<T> SelectRecursiveIterator<T>(IEnumerable<T> source, Func<T, IEnumerable<T>> getChildren)
{
var stack = new Stack<IEnumerator<T>>();
try
{
stack.Push(source.GetEnumerator());
while (0 != stack.Count)
{
var iter = stack.Peek();
if (iter.MoveNext())
{
T current = iter.Current;
yield return current;
var children = getChildren(current);
if (null != children) stack.Push(children.GetEnumerator());
}
else
{
iter.Dispose();
stack.Pop();
}
}
}
finally
{
while (0 != stack.Count)
{
stack.Pop().Dispose();
}
}
}
}
}