C# 覆盖树视图节点c中的计数#

C# 覆盖树视图节点c中的计数#,c#,count,treeview,overriding,C#,Count,Treeview,Overriding,我希望以适当的方式覆盖treeview节点中的计数,以便按特定文本或名称获取节点计数。有可能吗?提前谢谢 例如: 这就是我的树视图的样子 在这种情况下,如果我使用treeView1.Nodes[0].Nodes.Count,我将得到3,这是根目录中的节点数 我想要这样的东西,treeView1.Nodes[0].Nodes.CountByText(“文件夹”),它将返回我2,根节点中存在的节点(Text=“Folder”)的确切数量。写一个 然后,您可以执行以下操作: var count =

我希望以适当的方式覆盖treeview节点中的计数,以便按特定文本或名称获取节点计数。有可能吗?提前谢谢

例如:

这就是我的树视图的样子

在这种情况下,如果我使用treeView1.Nodes[0].Nodes.Count,我将得到3,这是根目录中的节点数

我想要这样的东西,treeView1.Nodes[0].Nodes.CountByText(“文件夹”),它将返回我2,根节点中存在的节点(Text=“Folder”)的确切数量。写一个

然后,您可以执行以下操作:

var count = treeview.CountByText("Folder");
根据您的喜好,您也可以传入TreeNodeCollection来执行此操作

编辑:

一些快速代码可以说明:

    static class Class1
    {
        public static int CountByText(this TreeView view, string text)
        {
            int count = 0;

           //logic to iterate through nodes and do count
            foreach (TreeNode node in view.Nodes)
            {
                nodeList.Add(node);
                Get(node);
            }
            foreach (TreeNode node in nodeList)
            {
                if (node.Text == text)
                {
                    count++;
                }
            }
           nodeList.Clear();
           return count;
        }

        static List<TreeNode> nodeList = new List<TreeNode>();
        static void Get(TreeNode node)
        {
            foreach (TreeNode n in node.Nodes)
            {
                nodeList.Add(n);
                Get(n);
            }
        }
     }
静态类Class1
{
公共静态int CountByText(此树视图,字符串文本)
{
整数计数=0;
//遍历节点并进行计数的逻辑
foreach(视图中的TreeNode节点。节点)
{
nodeList.Add(节点);
获取(节点);
}
foreach(节点列表中的TreeNode节点)
{
if(node.Text==Text)
{
计数++;
}
}
nodeList.Clear();
返回计数;
}
静态列表节点列表=新列表();
静态void Get(TreeNode节点)
{
foreach(node.Nodes中的树节点n)
{
添加节点列表(n);
Get(n);
}
}
}

这是我根据@Jaycee提供的代码修改的版本,我希望它能帮助其他人

public static class Extensions
{
    public static int CountByText(this TreeNode view, string text)
    {
        int count = 0;

        //logic to iterate through nodes and do count
        foreach (TreeNode node in view.Nodes)
        {
            if (node.Text == text)
            {
                count++;
            }
        }
        return count;
    }

}

如果我想要更具体的东西,比如我想要计算文件夹中的值,该怎么办?如果是treeview.CountByText(“Value”),我想它会给我3,但在上面的例子的基础上实际上是2。@shadow我又加了一些detail@overshadow另外,如果您想要2,而不是3,基于值只有2个唯一的父对象,那么只需修改方法中的逻辑即可反映这一点。或者修改扩展方法以接受Treenode参数而不是tree view。谢谢@Jayce,那么我怎么称呼它呢?我可以这样称呼它吗?treeview1.Nodes[“Root”].Nodes[“Folder”].CountByText(“Value”)?如果将参数类型更改为TreeNode,则会使其黯然失色。
public static class Extensions
{
    public static int CountByText(this TreeNode view, string text)
    {
        int count = 0;

        //logic to iterate through nodes and do count
        foreach (TreeNode node in view.Nodes)
        {
            if (node.Text == text)
            {
                count++;
            }
        }
        return count;
    }

}