将TreeNodeCollection转换为List <treenode>

时间:2018-05-24 00:04:47

标签: c# winforms .net-2.0

如何将TreeNodeCollection转换为List<TreeNode>

这不起作用。

ICollection tnc = treeview1.Nodes;
ICollection<TreeNode> tn = (ICollection<TreeNode>)tnc;
List<TreeNode> list = new List<TreeNode>(tn);

例外:

  

无法投射类型的对象   键入'System.Windows.Forms.TreeNodeCollection'   'System.Collections.Generic.ICollection`1 [System.Windows.Forms.TreeNode]'。

2 个答案:

答案 0 :(得分:0)

一个解决方案是:

List<TreeNode> treeNodeList = treeNodeCollection.OfType<TreeNode>().ToList();

另:

List<TreeNode> treeNodeList = treeNodeCollection.Cast<TreeNode>().ToList();

foreach Loop:

List<TreeNode> treeNodeList = new List<TreeNode>();
foreach (TreeNode item in treeNodeCollection)
    treeNodeList.Add(item);

答案 1 :(得分:0)

您可以使用以下用.NET 2.0编写的帮助程序类来展平TreeNodeCollection

using System.Collections.Generic;
using System.Windows.Forms;
public class NodeHelper
{
    public static List<TreeNode> ToList(TreeNodeCollection nodes)
    {
        List<TreeNode> list = new List<TreeNode>();
        foreach (TreeNode node in ToIEnumerable(nodes))
            list.Add(node);
        return list;
    }
    public static IEnumerable<TreeNode> ToIEnumerable(TreeNodeCollection nodes)
    {
        foreach (TreeNode c1 in nodes)
        {
            yield return c1;
            foreach (TreeNode c2 in ToIEnumerable(c1.Nodes))
            {
                yield return c2;
            }
        }
    }
}

例如,以下代码将treeView1的整个节点层次结构展平为一个列表:

List<TreeNode> list = NodeHelper.ToList(treeView1.Nodes);