Depth-first flattened collection of an object hierarchy using LINQ

后端 未结 4 922
你的背包
你的背包 2020-12-21 05:13

I have an object hierarchy (MasterNode -> ChildNodes) where master and child nodes are of the same type, and there are only two levels (top level and children) like this (\'

4条回答
  •  温柔的废话
    2020-12-21 06:07

    If you have a class like below

    public class Node
    {
        public string Name;
        public List Children = new List();
    }
    

    your linq would be

     Func, IEnumerable> Flatten = null;
     Flatten = coll => coll.SelectMany(n=>n.Concat(Flatten(n.Children)));
    

    Test Code:

    Node[] roots = new Node[]{ new Node(){Name="A"},new Node(){Name="B"},new Node(){Name="C"} };
    roots[0].Children.Add(new Node(){Name="D"});
    roots[0].Children.Add(new Node(){Name="E"});
    roots[0].Children.Add(new Node(){Name="F"});
    
    roots[1].Children.Add(new Node(){Name="G"});
    
    roots[2].Children.Add(new Node(){Name="H"});
    roots[2].Children.Add(new Node(){Name="I"});
    
    Func, IEnumerable> Flatten = null;
    Flatten = coll => coll.SelectMany(n=>n.Concat(Flatten(n.Children)));
    
    var result = String.Join(",",Flatten(roots).Select(x=>x.Name));
    
    Console.WriteLine(result);
    

提交回复
热议问题