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: