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()));

posted @ 2013-02-01 11:00  Ruiky  阅读(1517)  评论(0编辑  收藏  举报