c# - 将 TreeNodeCollection 转换为 List<TreeNode>

标签 c# winforms .net-2.0

如何转换 TreeNodeCollectionList<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);

关于c# - 将 TreeNodeCollection 转换为 List<TreeNode>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50499099/

相关文章:

c# - 测试和异常,模拟

.net - 如何增加asp.net中web服务的超时时间?

c# - 如何减少远程 SQL Server 负载?

c# - 如何访问另一个类中的事件处理程序

C# - SaveFileDialog 的上下文菜单错误

c# - 将一个属性绑定(bind)到另一个属性

.net - 是否有 Windows 窗体 native 方法来闪烁窗体的标题栏?

c# - 是否可以在迭代 ICollection 时确定当前位置?

c# - StreamWriter 用新文本替换行

c# - .Net 如何为用户控件的属性设置 IsReadOnly