Converting flattened hierarchical data from SQL Server into a structured JSON object with C#/Linq
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));
}