LINQ: How to convert the nested hierarchical object to flatten object

If you want it to flatten an arbitrarily deep tree of people, I suggest the following:

public IEnumerable<Person> GetFamily(Person parent)
{
    yield return parent;
    foreach (Person child in parent.Children) // check null if you must
        foreach (Person relative in GetFamily(child))
            yield return relative;
}

There isn’t really any good way to shorten this with LINQ, because anonymous lambdas can’t call themselves recursively without implementing Y. You could “reduce” the above method to

return parent.Children.SelectMany(p => GetFamily(p))
                      .Concat(new Person[] { parent });

or alternatively

yield return parent;
    foreach (Person relative in parent.Children.SelectMany(GetFamily))
        yield return relative;

but that seems sort of unnecessary to me.

Leave a Comment