How to flatten tree via LINQ?

后端 未结 14 2396
抹茶落季
抹茶落季 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:52

    A really other option is to have a proper OO design.

    e.g. ask the MyNode to return all flatten.

    Like this:

    class MyNode
    {
        public MyNode Parent;
        public IEnumerable Elements;
        int group = 1;
    
        public IEnumerable GetAllNodes()
        {
            if (Elements == null)
            {
                return Enumerable.Empty(); 
            }
    
            return Elements.SelectMany(e => e.GetAllNodes());
        }
    }
    

    Now you could ask the top level MyNode to get all the nodes.

    var flatten = topNode.GetAllNodes();
    

    If you can't edit the class, then this isn't an option. But otherwise, I think this is could be preferred of a separate (recursive) LINQ method.

    This is using LINQ, So I think this answer is applicable here ;)

提交回复
热议问题