我有对象的MyNode
树:如何过滤树结构?
public class MyNode
{
public int Type { get; set; }
public List<MyNode> Children { get; set; }
}
MyNode myRootNode;
// initializing a tree structure
所以我需要删除除了具有Type
财产
节点的所有节点等于包含
int myType
节点他们的子节点在
Type
属性的任何级别节点上等于int myType
我的方式:
bool Filter(MyNode node, MyNode parentNode, int type)
{
bool isFound = false;
if (node.Type == type)
isFound = true; // There's type
foreach (MyNode child in node.Children)
{
if (FilterTree(child, node, type))
isFound = true; // There is child node who has this type
}
// If there aren't this type neither any of its children has it
if (!isFound)
{
parentNode.Children.Remove(node);
}
return isFound;
}
我有一个exeption:Collection was modified; enumeration operation may not execute.
我想这是因为我删除列表中的元素。有没有办法以正确的方式做到这一点?或者我donig错了什么?
你确实需要修改的只是过滤初始集合(选择满足条件的项目)? – Dima 2013-03-06 18:06:23