Created
May 10, 2018 06:27
-
-
Save valerysntx/866e6813253c75e4c9f4b408f6481669 to your computer and use it in GitHub Desktop.
Traverse Nested Collections
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
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