Reputation: 380
I've created a dynamic tree for web application. My tree structure looks like:
id name pid data1 data2
1 Item1 0
2 Item2 1 70 45
3 Item3 0
4 Item3 1 56 48
3 Item3 3 34 48
........
The parent node doesn't contain any values for data1 and data2. I've created the recursive list for the tree. But now what i need to do is show the the values of data1 and data2 of all the child nodes into the values of data1 and data2 in parent node.
The tree is multilevel. How can i add to each parent the values of its child nodes? I am using C# btw. thanks
Update:
public class MyTree
{
public MyTree()
{
children = new List<MyTree>();
}
public int id { get; set; }
public string data { get; set; }
public int pid { get; set; }
public decimal? data1 { get; set; }
public decimal? data2 { get; set; }
public IList<MyTree> children { get; set; }
}
Upvotes: 0
Views: 1911
Reputation: 50114
The following member variable/updated property pair will give an explicit value if it's been set, or a recursive sum of all the children's values if it hasn't:
private decimal? _data1;
public decimal? data1
{
get
{
if (_data1.HasValue)
return _data1;
// This needs System.Linq but can be done manually.
return children.Sum(c => c.data1);
}
set { _data1 = value; }
}
(Similarly for data2
.)
It doesn't stop you from explicitly setting a value on an element with children.
Upvotes: 1