I have the following two methods which loop either a TreeView or TreeNode which I want to combine into a single method. Instead of passing the TreeView/TreeNode I could pass an Object and check the type but wanted to know if there was better way?
private TreeNode SearchNode(string nodetext, TreeNode node)
{
foreach (TreeNode nd in node.Nodes)
{
if (nd.Text == nodetext)
{
return nd;
}
}
return null;
}
private TreeNode SearchParentNode(string nodetext, TreeView trv)
{
foreach (TreeNode node in trv.Nodes)
{
if (node.Text == nodetext)
{
return node;
}
}
return null;
}
You want a single method that can search for a value in a NodesCollection, so just extract the contents of both methods into a single, third method that accepts a NodesCollection:
private TreeNode SearchNodes(string nodeText, TreeNodesCollection nodes)
{
foreach (TreeNode node in nodes)
{
if (node.Text == nodeText)
{
return node;
}
}
return null;
}
And pass it whatever collection you want to search:
return SearchNodes(nodetext, node.Nodes);
return SearchNodes(nodetext, trv.Nodes);
Also, you can reduce the SearchNodes method to a single line using LINQ:
private TreeNode SearchNodes(string nodeText, TreeNodesCollection nodes)
{
return nodes.Cast<TreeNode>().FirstOrDefault(n => n.Text == nodeText);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With