How to flatten tree via LINQ?

后端 未结 14 2176
抹茶落季
抹茶落季 2020-11-22 04:56

So I have simple tree:

class MyNode
{
 public MyNode Parent;
 public IEnumerable Elements;
 int group = 1;
}

I have a I

14条回答
  •  囚心锁ツ
    2020-11-22 05:39

    You can flatten a tree like this:

    IEnumerable Flatten(IEnumerable e) =>
        e.SelectMany(c => Flatten(c.Elements)).Concat(new[] { e });
    

    You can then filter by group using Where(...).

    To earn some "points for style", convert Flatten to an extension function in a static class.

    public static IEnumerable Flatten(this IEnumerable e) =>
        e.SelectMany(c => c.Elements.Flatten()).Concat(e);
    

    To earn more points for "even better style", convert Flatten to a generic extension method that takes a tree and a function that produces descendants from a node:

    public static IEnumerable Flatten(
        this IEnumerable e
    ,   Func> f
    ) => e.SelectMany(c => f(c).Flatten(f)).Concat(e);
    

    Call this function like this:

    IEnumerable tree = ....
    var res = tree.Flatten(node => node.Elements);
    

    If you would prefer flattening in pre-order rather than in post-order, switch around the sides of the Concat(...).

提交回复
热议问题