Here is my suggestion for you. Create a data object (choose a better name and add some more properties if necessary) like this
public class DataNode
{
public int Id { get; private set; }
public string Name { get; set; }
public List<DataNode> Children { get; private set; }
public DataNode(int id, string name)
{
Id = id;
Name = name;
Children = new List<DataNode>();
}
}
Create a list of those nodes like var dataNodeList = new List<DataNode>();
and add all element who don't have a parent directly to that list. Add each children to the Children
list of the parent with parentid
. To find a parent in your tree use this function:
public DataNode FindElementById(IEnumerable<DataNode> elementsToSearch, int id)
{
foreach (var dataNode in elementsToSearch)
{
if (dataNode.Id == id)
{
return dataNode;
}
var found = FindElementById(dataNode.Children, id);
if (found != null)
{
return found;
}
}
return null;
}