I used a Tree control to view some hierarchical items base on a nested (parent child) table .
Every node has a NameValue format that accept either a name and value .
But only Leaves (last nodes) have integer values and values of parents are left blank (just the Names they have) .
I want to summarize values so that every parent hold the sum of it's sub nodes and leaves values .
I think recursion or maybe LINQ is needed to accomplish this task but i don't know how ?
maybe some pseudo code will be helpful for me .
Thanks i开发者_JAVA技巧n advance for the help!
This is untested but i think it might work to set all the values of all nodes:
public void SetNodeValues(Node node)
{
if (node.Name == String.Empty)
{
//If it has no name it is a leaf, which needs no value
return;
}
else
{
//Make sure all child-nodes have values
foreach (var childNode in node.ChildNodes)
{
SetNodeValues(childNode);
}
//Sum them up and set that as the current node's value
node.Value = node.ChildNodes.Sum(x => x.Value);
}
}
This will do it for you :
class Node
{
public Node()
{
Children = new List<Node>();
}
public IEnumerable<Node> GetSubTree()
{
return Children.SelectMany(c => c.GetSubTree()).Concat(new[] { this });
}
public List<Node> Children { get; set; }
public string Value { get; set; }
}
class Tree
{
public Tree()
{
Root = new Node();
}
public IEnumerable<Node> GetAllNodes()
{
return Root.Children.SelectMany(root => root.GetSubTree());
}
Node Root { get; set; }
//This is the Property you want:
public int GetValuesSum
{
get
{
return GetAllNodes().Where(node => !string.IsNullOrEmpty(node.Value)).Sum(node => Convert.ToInt32(node.Value));
}
}
}
Reference : How can I get a List from all nodes in a tree using LINQ?
精彩评论