我有一棵对象树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;
}
我有一个例外:Collection was modified; enumeration operation may not execute.
我认为那是因为我删除了列表中的元素。有没有办法以正确的方式做到这一点?或者我做错了什么?