Domanda

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)?

È stato utile?

Soluzione

Just put it in a static helper class like:

public static class CustomTreeNodeExtensions
{
    public static IEnumerable<TreeNode> Descendants(this TreeNode root)
    {
        // method
    }
}

Extensions are required to be in a static class.

BUT IF you create a CustomTreeNode class anyhow why do you want it to be an extension method if you add it to the class directly? Why not make it a normal method (If you just created CustomTreeNode for the extension this is irrelevant - in that case: the class containing the extension method is NOT required to inherit from the class you are trying to create the extension method for)?

public class CustomTreeNode : TreeNode
{
    public IEnumerable<TreeNode> Descendants()
    {
        var nodes = new Stack<TreeNode>(new[] { this });
        // rest
    }
}

Altri suggerimenti

You have to declare the extension method in separate, static class.

public static class NodeExtensions
{
    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);
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top