Last active
October 5, 2020 13:50
-
-
Save fiddyschmitt/b4bb35cb0f65a22ecf1ce9ed977722a0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static IEnumerable<T> Recurse<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> childSelector, bool depthFirst = false) | |
{ | |
List<T> queue = new List<T>(source); ; | |
while (queue.Count > 0) | |
{ | |
var item = queue[0]; | |
queue.RemoveAt(0); | |
var children = childSelector(item); | |
if (depthFirst) | |
{ | |
queue.InsertRange(0, children); | |
} | |
else | |
{ | |
queue.AddRange(children); | |
} | |
yield return item; | |
} | |
} | |
public static IEnumerable<T> Recurse<T>(this T source, Func<T, T> childSelector, bool depthFirst = false) | |
{ | |
var list = new List<T>() { source }; | |
var childListSelector = new Func<T, IEnumerable<T>>(item => | |
{ | |
var child = childSelector(item); | |
if (child == null) | |
{ | |
return new List<T>(); | |
} | |
else | |
{ | |
return new List<T>() { child }; | |
} | |
}); | |
foreach (var result in Recurse(list, childListSelector, depthFirst)) | |
{ | |
yield return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment