I have the following node:
class Node
{
public string Name;
public IEnumerable<Node> Children;
}
I have the following extension method:
public static class ExtensionMethods
{
public static IEnumerable<Node> TraverseTree(this Node root)
{
if (root.Children != null)
{
foreach (var child in root.Children)
{
var nodes = TraverseTree(child);
foreach (var node in nodes)
{
yield return node;
}
}
}
yield return root;
}
}
I want to search for a node in the tree with the name "Foo". In order to do so I do:
Node myNode = /* some large tree! */
var search = myNode.TraverseTree().Where(x=>x.Name == "Foo").FirstOrDefault();
I have 3 goals
TraverseTree
traverse the tree with yield (IEnumerable) so that if the 3th node happens have the name == "Foo" then I do not have to traverse the entire tree. Right now this case is true. TraverseTree
run on a separate thread because it may take a long time to find. Therefore I guess the TraverseTree
method should take a callBack parameter?What is the correct way of doing this?
Sorry I forgot to mention I am using .Net Framework 4.0
CancellationToken
that is checked by either the traversal algorithm, your child selector, or both, is certainly something you could add. The other option is to just have whatever it is that's waiting on the result of the traversal stop waiting, rather than trying to actually stop the computation from happening.