将 TreeNodeCollection 转换为列表<TreeNode>

Convert TreeNodeCollection to List<TreeNode>

如何将 TreeNodeCollection 转换为 List<TreeNode>

这不起作用。

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

异常:

Unable to cast object of type 'System.Windows.Forms.TreeNodeCollection' to type 'System.Collections.Generic.ICollection`1[System.Windows.Forms.TreeNode]'.

一个解决方案是:

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

另一个:

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

foreach 循环:

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

您可以使用以下用 .NET 2.0 编写的帮助程序 class 展平 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);