Flatten a tree into an enumeration


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// Flattens any tree into an enumeration
  3. /// </summary>
  4. /// <typeparam name="T"></typeparam>
  5. /// <param name="item"></param>
  6. /// <param name="next"></param>
  7. /// <returns></returns>
  8. public static IEnumerable<T> Flatten<T>(T item, Func<T, IEnumerable<T>> next)
  9. {
  10. yield return item;
  11. foreach (T child in next(item))
  12. foreach (T flattenedChild in Flatten(child, next))
  13. yield return flattenedChild;
  14. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.