Reputation: 83
I'm trying to build a hierarchy of data and I have the following code:
public class TreeData
{
public string parent { get; set; }
public string child { get; set; }
public List<TreeData> thisTree { get; set; }
public void Add(string parent, string child)
{
this.parent = parent;
this.child = child;
}
public void Add(List<TreeData> myList)
{
this.thisTree = myList;
}
}
I also have this to use it:
TreeData myTree = new TreeData();
myTree.Add("Alan", "Dan");
TreeData myTree1 = new TreeData();
myTree1.Add("Dan", "Heidi");
myTree1.Add(myTree);
However I can't pass myTree
to my Add
method as it is not a List
, what do I need to do to be able to pass myTree
back to my class?
Thanks, Dan
Upvotes: 0
Views: 105
Reputation: 169
For a tree-like class, I suggest using the following structure :
public class TreeData
{
public TreeData Parent { get; private set; }
public string ID { get; private set; }
public List<TreeData> Child { get; private set; }
//Constructor for root objects
public TreeData(string id) : this(null, id)
{
}
//Constructor for child objects
public TreeData(TreeData parent, string id)
{
this.ID = id;
this.Parent = parent;
this.Child = new List<TreeData>();
}
public TreeData Add(string childID)
{
TreeData child = new TreeData(this, childID);
this.Child.Add(child);
return child;
}
}
This way each node has access to parent and childs
TreeData alanNode = new TreeData("Alan");
TreeData danNode = alanNode.Add("Dan");
danNode.Add("Heidi");
Upvotes: 1
Reputation: 101732
I guess all you need to do is something like this:
public class TreeData
{
private TreeData _child;
public string Name { get; set; }
public TreeData Next
{
get { return _child; }
set { _child = value; }
}
}
TreeData myTree = new TreeData("root");
TreeData child1 = new TreeData("child1");
TreeData child2 = new TreeData("child2");
myTree.Next = child1;
child1.Next = child2;
If you want one TreeData might have more than one child you could extend this class like this:
public class TreeData
{
private TreeData _parent;
private List<TreeData> childs = new List<TreeData>();
public TreeData(string name)
{
Name = name;
}
public void AddChild(TreeData child)
{
child.Parent = this;
childs.Add(child);
}
public string Name { get; set; }
public TreeData Parent
{
get { return _parent; }
set { _parent = value; }
}
public List<TreeData> Childs
{
get { return childs; }
}
}
Then:
TreeData myTree = new TreeData("root);
TreeData child1 = new TreeData("child1");
TreeData child2 = new TreeData("child2");
myTree.AddChild(child1);
myTree.AddChild(child2);
Upvotes: 0
Reputation: 1777
Why don't you change the signature of
public void Add(string parent, string child)
to
public void Add(TreeData parent, TreeData child)
Upvotes: 0