szabototo89 / CodeSharper

Refactoring tool, written in C# and using TDD for developing
2 stars 0 forks source link

[code snippet] Flatten Tree #14

Open szabototo89 opened 10 years ago

szabototo89 commented 10 years ago

Source: http://snipplr.com/view/37224/

/// <summary>
/// Flattens any tree into an enumeration
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="item"></param>
/// <param name="next"></param>
/// <returns></returns>
public static IEnumerable<T> Flatten<T>(T item, Func<T, IEnumerable<T>> next)
{
    yield return item;
    foreach (T child in next(item))
        foreach (T flattenedChild in Flatten(child, next))
            yield return flattenedChild;
}