Building hierarchy objects from flat list of parent/child

前端 未结 6 509
花落未央
花落未央 2021-01-30 18:07

I have a list of items in a hierarchy, and I\'m attempting to parse this list out into an actual hierarchy of objects. I\'m using modified pre-order tree traversal to store/iter

6条回答
  •  盖世英雄少女心
    2021-01-30 18:38

    Here is an example, hope this helps

    class Program
    {
        static void Main(string[] args)
        {
            TreeObject a  = new TreeObject() { Name = "Item A" };
            a.Children.Add( new TreeObject() { Name = "Item A.1" });
            a.Children.Add( new TreeObject() { Name = "Item A.2" });
    
            TreeObject b = new TreeObject() { Name = "Item B" };
            b.Children.Add(new TreeObject() { Name = "Item B.1" });
            b.Children.Add(new TreeObject() { Name = "Item B.2" });
    
            TreeObject c = new TreeObject() { Name = "Item C" };
    
            List nodes = new List(new[] { a, b, c });
    
            string list = BuildList(nodes);
            Console.WriteLine(list); // Item A,Item A.1,Item A.2,Item B,Item B.1,Item B.2,Item C
    
            List newlist = new List();
            TreeObject temp = null;
    
            foreach (string s in list.Split(','))
            {
                if (temp == null || !s.Contains(temp.Name) || temp.Name.Length != s.Length)
                {
                    temp = new TreeObject() { Name = s };
                    newlist.Add(temp);
                }
                else
                {
                    temp.Children.Add(new TreeObject() { Name = s });
                }                              
            }
    
            Console.WriteLine(BuildList(newlist)); // Item A,Item A.1,Item A.2,Item B,Item B.1,Item B.2,Item C
        }
    
        static string BuildList(List nodes)
        {
            StringBuilder output = new StringBuilder();
            BuildList(output, nodes);
            return output.Remove(output.Length - 1, 1).ToString();
        }
    
        static void BuildList(StringBuilder output, List nodes)
        {
            foreach (var node in nodes)
            {
                output.AppendFormat("{0},", node.Name);
                BuildList(output, node.Children);
            }
        }
    }
    
    public class TreeObject
    {
        private List _children = new List();
    
        public string Name { get; set; }
        public Guid Id { get; set; }
        public List Children { get { return _children; } }
    }
    

    }

提交回复
热议问题