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 children = new List(); public List 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 erarchicalNode(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 0); foreach (var node in query) { var current = root; foreach (string part = node. Split(new {'/'}, StringSplitOptions.

RemoveEmptyEntries)) { int parsedPart = int. Parse(part); current = current. ChildrenparsedPart - 1; } current.Children.

Add(new Name, node. Id)); }.

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 rather than a List 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 erarchicalNode { private readonly List children = new List(); public List 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 erarchicalNode(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 0); foreach (var node in query) { var current = root; foreach (string part = node. Split(new {'/'}, StringSplitOptions.

RemoveEmptyEntries)) { int parsedPart = int. Parse(part); current = current. ChildrenparsedPart - 1; } current.Children.

Add(new Name, node. Id)); }.

Worked like a charm. Thanks! – Justin Rusbatch Aug 4 at 18:11 @Justin: Glad to help - sorry I couldn't actually give the full code; I assume you had to fix it up a bit, given the later information.

– Jon Skeet Aug 4 at 18:30.

Var query = context.Nodes. OrderBy(x => x. Foreach (string part = node.HierarchyPath.

Int parsedPart = int. Current = current.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions