C# - LINQ: Flatten a hierarchy

By , 8/6/2016
(0 ratings)
This extension method flattens a hierarchical structure.
For example, if you have a Windows Forms project with a TreeView and you want transfer all items into a ListBox, than my method provides a single-line-solution.
.SelectMany(x => x.Flatten(y => y.Nodes.Cast<TreeNode>()))
.Select(x => (object)x.Text)

The call of the Cast<T> methods is required because the TreeNodeCollection does not implement the generic IEnumerable<T> interface.

Required Namespaces
/// <summary>
/// Flattens a hirarical object structure.
/// </summary>
/// <typeparam name="T">The type of the elements inside the structure.</typeparam>
/// <param name="item">The root object which sub-elements will be flattened. The item will be included in the result as the first item.</param>
/// <param name="selector">A function which selects the sub-elements.</param>
/// <returns>A collection with the sub-elements under <paramref name="item"/> inclusive <paramref name="item"/> itself.</returns>
public static IEnumerable<T> Flatten<T>(this T item, Func<T, IEnumerable<T>> selector)
    yield return item;
    foreach (var subSubItem in selector(item).SelectMany(subItem => Flatten(subItem, selector)))
        yield return subSubItem;
Tagged with LINQ, List, Extension, Tree, TreeView, Hierachie, Flat.



Log in, to comment!