I have the following SQL table data:
The visual tree should look something like this:
To get the very top nodes I'm using:
var parentNodes = data
.Where(i => i.AncestorId == i.DescedantId &&
(data.Count(d => d.DescedantId == i.DescedantId) == 1))
.ToList();
Any clue on how to build a function that would loop trough the structure and then build the tree style object?
My tree style object classes are:
public class ProfitCenterRoot
{
public List<ProfitCenterItem> Data { get; set; }
}
public class ProfitCenterItem
{
public int AncestorId { get; set; }
public int DescendantId { get; set; }
public string Text { get; set; }
public bool Leaf { get; set; }
// These are the child items
public List<ProfitCenterItem> Data { get; set; }
}
You can use recursion to add children to each parent. But first, I would add a default constructor to your classes to initialize the Data lists:
Then you can create a simple method that takes in a Parent and a list of all children, recursively add children to each child of the parent, and then add the children to the parent:
So to populate your objects, you could then do:
I think I have an even easier way to build the tree.
First up though, it seems odd to have the properties
AncestorId
&DescendantId
for each node, so I simplified the structure to justId
like this:Now it becomes easy.
The nodes that are actually relevant are those where
AncestorId != DescendantId
so we get those:Now the parent nodes are simply those ids that appear on the left but don't appear on the right. Like this:
Now to build the tree we create a lookup for the children:
Here's the trickiest part - a recursive build function for traversing the lookup to build all the nodes:
Finally we just need to create the root node and call
build
to create the parent nodes:Here's the result I get: