LINQ查询遍历树视图并获取数据 [英] LINQ Query to traverse treeview and get data

查看:59
本文介绍了LINQ查询遍历树视图并获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在treeView中加载了自定义类集合(例如MyClass).我想从已检查的树视图项目中返回MyClass []的集合,并希望使用LINQ.我在下面尝试,效果很好.但是我想编写1行Linq查询,甚至不使用List<>.有什么帮助吗?是否可以在1 Linq查询中进行递归?

I having treeView loaded with custom class collection(eg: MyClass). I want return collection of MyClass[] from the checked tree view items and want use LINQ. I try below and it work fine. But i want to write 1 line Linq query without even using the List<>. Any help ? Is it possible to have recursion within the 1 Linq query ?

List<MyClass> items = new List<MyClass>();            
items.AddRange(from node in tvData.Nodes.OfType<TreeNode>().Where((x) => x.Checked)
               select node.Tag as MyClass);

tvData.Nodes.OfType<TreeNode>()
            .ForEach((x => items.AddRange(from item in x.Nodes.OfType<TreeNode>()
                                                        .Where((y) => y.Checked)
                                          select item.Tag as MyClass)));

return items.ToArray();

注意:treeView的层深度为1.每个父节点都有一组子节点,并且只有一个级别.

Note : The treeView having 1 level depth. Every parent node have a set of child nodes and only 1 level.

推荐答案

尝试一下:

return tvData.Nodes
             .OfType<TreeNode>()
             .SelectMany(x => new[]{ x }.Concat(x.Nodes.OfType<TreeNode>()))
             .Where(x => x.Checked)
             .Select(x => x.Tag as MyClass)
             .ToArray();

一个以上级别的解决方案可能看起来像这样:

A solution for more than one level could look like this:

IEnumerable<TreeNode> GetNodeAndChildren(TreeNode node)
{
    return new[]{ node }.Concat(node.Nodes
                                    .OfType<TreeNode>()
                                    .SelectMany(x => GetNodeAndChildren(x)));
}

return tvData.Nodes
             .OfType<TreeNode>()
             .SelectMany(x => GetNodeAndChildren(x))
             .Where(x => x.Checked)
             .Select(x => x.Tag as MyClass)
             .ToArray();

这篇关于LINQ查询遍历树视图并获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆