2011-04-17 61 views
2

我使用树控件来查看基于嵌套(父子)表的一些分层项目。汇总树上的值

每个节点都有一个NameValue格式,它接受名称和值。

但是只留下叶子(最后节点)有整数值和父母的值留空(只是他们的名字)。

我想汇总一些值,以便每个父节点都保存其子节点和树叶值的总和。

我认为需要递归或LINQ来完成这个任务,但我不知道如何?

也许一些伪代码对我会有帮助。

在此先感谢您的帮助!

回答

1

这是未经测试,但我认为它可能工作来设置所有节点的所有值:

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); 
    } 
} 
+0

请测试它,不工作。 – 2011-04-17 07:03:36

+0

非常感谢H.B 您的解决方案很有帮助,它解决了我的问题。 这是整洁和健壮。 – 2011-04-17 09:20:48

+0

谢谢,知道它应该工作,现在我去了没有测试它的麻烦。 – 2011-04-17 09:35:26

0

这会为你做它:

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)); 
     } 
    } 
} 

参考:How can I get a List from all nodes in a tree using LINQ?

+0

这不是一棵树,它是一个森林-_- – 2011-04-17 06:37:34

+0

@HB我将它改为树;) – 2011-04-17 06:41:42

+0

哈哈,不错,但我仍然想知道这是否适用于OP,目标数据结构有点不明显描述。他/她也想设置分支节点的值,而不仅仅是总和。 – 2011-04-17 06:47:01