Skip to content

Instantly share code, notes, and snippets.

@fiddyschmitt
Last active October 5, 2020 13:50
Show Gist options
  • Save fiddyschmitt/b4bb35cb0f65a22ecf1ce9ed977722a0 to your computer and use it in GitHub Desktop.
Save fiddyschmitt/b4bb35cb0f65a22ecf1ce9ed977722a0 to your computer and use it in GitHub Desktop.
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