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()));
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步