Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save valerysntx/866e6813253c75e4c9f4b408f6481669 to your computer and use it in GitHub Desktop.
Save valerysntx/866e6813253c75e4c9f4b408f6481669 to your computer and use it in GitHub Desktop.
Traverse Nested Collections
using System.Linq;
namespace System.Collections.Generic
{
public static class NestedCollectionsExtentions
{
public static IEnumerable<T> Traverse<T>(this T node, Func<T, IEnumerable<T>> childrenFor)
{
yield return node;
IEnumerable<T> enumerable = childrenFor(node);
if (enumerable != null)
{
foreach (T current in enumerable.SelectMany((T n) => n.Traverse(childrenFor)))
{
yield return current;
}
}
yield break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment