# Winform TreeView 查找下一个节点

```public static class TreeViewHelper
{
private static IEnumerable<TreeNode> childNodes(this TreeNode node)
{
return node.Nodes.Cast<TreeNode>()
.SelectMany(x => x.selfAndChildNodes());
}

private static IEnumerable<TreeNode> selfAndChildNodes(this TreeNode node)
{
return new List<TreeNode>() { node }
.Union(node.Nodes.Cast<TreeNode>()
.SelectMany(x => x.selfAndChildNodes()));
}

private static IEnumerable<TreeNode> nextNodes(this TreeView tree, TreeNode node)
{
bool after = false;
if (node.Parent == null)
return tree.Nodes.Cast<TreeNode>()
.Select(x => { bool b = after = after || (node == x); return new { x, b }; })
.Where(x => x.b && x.x != node)
.SelectMany(x => new List<TreeNode>() { x.x }.Union(x.x.childNodes()));
else
return node.Parent.Nodes.Cast<TreeNode>()
.Select(x => { bool b = after = after || (node == x); return new { x, b }; })
.Where(x => x.b && x.x != node)
.SelectMany(x => new List<TreeNode>() { x.x }.Union(x.x.childNodes()))
.Union(tree.nextNodes(node.Parent));
}

public static IEnumerable<TreeNode> NextNodes(this TreeView tree, TreeNode node)
{
if (tree == null || node == null)
return new List<TreeNode>();
return node.childNodes().Union(tree.nextNodes(node));
}

public static IEnumerable<TreeNode> NextNodes(this TreeView tree)
{
if (tree == null || tree.SelectedNode == null)
return new List<TreeNode>();
return tree.NextNodes(tree.SelectedNode);
}
}```

如何调用：

var tn = _Tv.NextNodes().FirstOrDefault(x => Regex.IsMatch(x.Text, "(?i)" + txtKey.Text.Trim()));

if (tn == null)

MessageBox.Show("查找完毕");

else

_Tv.SelectedNode = tn;

```public static IEnumerable<TreeNode> TreeWhere(this TreeNodeCollection tds, Func<TreeNode, bool> Fun)
{
foreach (TreeNode item in tds)
{
if (Fun(item))
yield return item;

var list = item.Nodes.TreeWhere(Fun);
foreach (var item1 in list)
yield return item1;
}
}```

var tn = treeView1.Nodes.TreeWhere(x => Regex.IsMatch(x.Text, @"(?i)" + txtKey.Text.Trim()));

709 篇文章53 人订阅

0 条评论

## 相关文章

11510

1.1K10

32270

23990

### 【开源】QuickPager ASP.NET2.0分页控件V2.0.0.1——分页控件的源码 （二）

namespace JYK.Controls.PageManage {     /**//// <summary>     /// 生成分页控件需要的SQL语句...

22660

### C#中格式化数据的输出

alignment:可选，是一个带符号的整数，指示首选的格式化字段宽度。如果“对齐”值小于格式化字符串的长度，“对齐”会被忽略，并且使用格式化字符串的长度作为字...

11200

48710

### RavenDb学习（五）结果转换

1）Result Transformers public class Order { public DateTime OrderedAt { get;...

28190

16810

294100