Ich möchte eine Methode implementieren, die es mir ermöglicht, einen Knoten in einem Baum zu finden. Die Art, wie ich es mache, verwendet rekursiv globale Variablen, um zu wissen, wann ich aufhören soll.Knoten beim Query Tree suchen
Ich habe die Klasse:
class Node // represents a node in the tree
{
// constructor
public Node() {
Children = new List<Node>();
}
public List<Node> Children;
public string Name;
public string Content;
}
Und die Methode, die ich jetzt habe, ist:
private bool IsNodeFound = false; // global variable that I use to decide when to stop
// method to find a particular node in the tree
private void Find(Node node, string stringToFind, Action<Node> foundNode)
{
if(IsNodeFound)
return;
if (node.Content.Contains(stringToFind)){
foundNode(node);
IsNodeFound =true;
}
foreach (var child in node.Children)
{
if (child.Content.Contains(stringToFind)){
foundNode(node);
IsNodeFound =true;
}
Find(child, stringToFind, foundNode);
}
}
und die Art, wie ich die Find-Methode verwenden, ist wie:
// root is a node that contain children and those children also contain children
// root is the "root" of the tree
IsNodeFound =false;
Node nodeToFind = null;
Find(root, "some string to look for", (x)=> nodeToFind=x);
Also meine Frage ist wie kann ich diese Methode eleganter machen. Ich werde wie die Signatur der Methode aussehen:
public Node FindNode(Node rootNode);
Ich denke, es ist überflüssig, was soll ich tun, und es ist wahrscheinlich eine bessere Möglichkeit, dieses Verfahren zu schaffen. Oder vielleicht könnte ich die Node-Klasse ändern, so dass ich dasselbe mit einer linq-Abfrage erreichen kann.
+1 Es ist toll, weil ich nach beliebigen Kriterien wie filtern. 'Root.GetSubTree() FirstOrDefault (x => x.Name == "Foo") 'Vielen Dank! –
So eine saubere, präzise Antwort. – AndyUK