Converting flattened hierarchical data from SQL Server into a structured JSON object with C#/Linq

后端 未结 1 1392
既然无缘
既然无缘 2020-11-29 08:01

I am developing an MVC app that retrieves data from a table in SQL Server that is structured like so:

+-----------------------------------+
| Id | Name   | H         


        
相关标签:
1条回答
  • 2020-11-29 08:16

    EDIT: I don't have time to fix the answer below right now, but given the extra information in the question, I suspect you want to keep a Dictionary<int, HierarchicalNode> rather than a List<HierarchicalNode> so that you're not relying on any ordering...


    I would forget about the JSON representation to start with, and concentrate on building an in-memory POCO representation of the hierarchy. To do that, I'd use something like this:

    class HierarchicalNode
    {
        private readonly List<HierarchicalNode> children =
            new List<HierarchicalNode>();        
        public List<HierarchicalNode> Children { get { return children; } }
    
        private readonly string name;
        public string Name { get { return name; } }
    
        private readonly int id;
        public int Id { get { return id; } }
    
        public HierarchicalNode(string name, int id)
        {
            this.name = name;
            this.id = id;
        }
    }
    

    Then build up the tree like this:

    // Make sure we get everything in a sensible order, parents before children
    var query = context.Nodes.OrderBy(x => x.Depth);
    
    var root = new HierarchicalNode("Root", 0);
    foreach (var node in query)
    {       
        var current = root;
        foreach (string part = node.HierarchyPath.Split(new[] {'/'},
                                       StringSplitOptions.RemoveEmptyEntries))
        {
            int parsedPart = int.Parse(part);
            current = current.Children[parsedPart - 1];
        }
        current.Children.Add(new HierarchicalNode(node.Name, node.Id));
    }
    
    0 讨论(0)
提交回复
热议问题