Search for all objects of type T in the C # tree structure

I need to write a tree search method that takes a parameter of type T and returns all elements of type T that exist in the tree. Is there any way to do this? I would prefer elegance over efficiency at this point ...

+4
source share
4 answers

Something like that:

internal static IEnumerable<T> AllDescendantNodes<T>( this TreeNode input ) where T class; { T current = null; foreach ( TreeNode node in input.Nodes ) if( (current = node as T) != null ) { yield return current; foreach ( var subnode in node.AllDescendantNodes<T>() ) yield return subnode; } } 

Then you call this against the root of the node as an extension method:

 foreach( MyCustomNodeClass item in rootNode.AllDescendantNodes<MyCustomNodeClass>() ) { ... } 
+2
source

Well, internally, the method would have to iterate over all the elements of the tree, so moving to a simple enumeration on it and using the OfType LINQ method is not so far:

 var onlyTs = yourTree.OfType<SomeT>(); 
+2
source

Assuming your tree is shared. those. Item<T> .

 int count = yourTree.Count(p => p == typeof(T)); 

Otherwise, analyze each node and compare " item == typeof(T) "

+1
source

You need the basic tree traversal function (preorder, inorder or postorder - it doesn't matter) and the filter function. Then you can put these two together and get what you need:

 IEnumerable<T> Traverse(Tree<T> tree) { yield return tree.Data; foreach(Tree<T> subtree in tree.Subtrees) foreach(T t in Traverse(subtree)) yield return t; } IEnumerable<U> Filter<T, U>(IEnumerable<T> source) where U : T { foreach(T t in source) if(t is U) yield return (U)t; } 
+1
source

All Articles