I have a treeview, and want to simply return the deepest node that satisfies a given condition.
The answer to this question is the most promising so far: Searching a tree using LINQ
So I could do this:
foreach(CustomTreeNode aNode in treMyTreeView.Nodes){
List<TreeNode> EligibleNodes =
aNode.Descendants().Where(node => node.Tag == SomeCondition)
}
(I realise I might have a bit more work to do to cast from TreeNode to CustomTreeNode)
But before I even get there, I'm getting stuck trying to add the extension method to the TreeNode class.
public class CustomTreeNode : TreeNode {
static IEnumerable<TreeNode> Descendants(this TreeNode root) {
var nodes = new Stack<TreeNode>(new[] { root });
while (nodes.Count > 0) {
TreeNode node = nodes.Pop();
yield return node;
foreach (TreeNode n in node.Nodes) nodes.Push(n);
}
}
}
You'll tell me it needs to be static, and therefore I can't derive from TreeNode. And I don't understand why.
How can I achieve the above (or something similar)?