简体   繁体   中英

How to filter tree structure?

I have a tree of objects MyNode :

public class MyNode
{
   public int Type { get; set; }
   public List<MyNode> Children { get; set; }
}

MyNode myRootNode;
// initializing a tree structure

So I need to remove all nodes except

  1. Nodes that have Type property is equal to int myType

  2. Nodes that contains in their child nodes at any level nodes with Type property is equal to int myType

My way:

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

I've got an exeption: Collection was modified; enumeration operation may not execute. Collection was modified; enumeration operation may not execute. I think that's because I deleting elements in the list. Is there a way to do it the right way ? Or what am I donig wrong ?

Assuming the root node is always retained, you can remove the children in the mathod, not the node itself.

bool Filter(MyNode node,int type)
{
//remove children
foreach(MyNode child in node.Children.Where(c=>!Filter(c, type)).ToArray())
    node.Children.Remove(child);
//return if should be retained
return node.Type==type || node.Children.Count>0;
}

Linq comes to rescue you:

public static void RemoveNodesRecursive(this MyNode node, Predicate<MyNode> predicate)
{
    node.Children.RemoveAll(predicate);
    foreach (var n in node.Children)
    {
        RemoveNodes(n);
    }
}

and then start with the root node:

myRootNode.RemoveNodesRecursive(n => n.node.Type == myType)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM