如何解决异常:集合被修改;枚举操作可能无法执行 [英] How to solve the Exception: Collection was modified; enumeration operation may not execute

查看:103
本文介绍了如何解决异常:集合被修改;枚举操作可能无法执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何解决异常:修改了集合;枚举操作可能无法执行



这里的迭代工作正常但同时我想删除那些子节点..我可以知道怎么办?



How to solve the Exception: Collection was modified; enumeration operation may not execute

Here the iterations are working fine but meanwhile i want to delete those child nodes.. may i knw how can i ?

private void PrintRecursive(TreeNode treeNode, TreeView treeviewtemp2)
   {

      // (level-2 TreeNodes)
       int x = 0;
       foreach (TreeNode n in treeNode.ChildNodes)
       {
          

           var nodeName = n.Text;
           var nodeValue = n.Value;

           treeviewtemp2.Nodes[0].ChildNodes[x].ChildNodes.Remove(n);
           x++;

       }

   }





提前致谢



Thanks in advance

推荐答案

使用 foreach 遍历它时不要修改集合。实际上,这并不是真的需要。例如,您可以创建要删除的元素引用列表,并在单独的循环中将它们全部删除。顺便说一句,这种限制不适用于 for 循环,但你必须格外小心。例如,如果要删除某些元素,一种常用技术是反向遍历集合。 (我是否必须解释原因?这是非常简单的逻辑。)



您的代码确实存在问题,因此这个傻瓜式.NET功能确实对您有所帮助。首先,当你取一些索引( [0],[x],n )时,你必须确保该索引处的元素确实存在。



我会为你的家庭练习重写你的代码。学习如何自己解决这些小问题非常重要。



(另一个暗示:如果你想使用,计算计数并将其存储在循环之前的某个局部变量中。再次,我希望我不必解释原因。)



-SA
Don't modify the collection during traversing it using "foreach". Actually, this is not really needed. For example, you can create a list of element references to be removed, and remove them all in a separate loop. By the way, such limitation is not applied to "for" loop, but you have to be extra careful. For example, one usual technique is to traverse the collection in reverse, if you are going to remove some elements. (Do I even have to explain why? This is really simple logic.)

Your code really have problems, so this fool-prof .NET feature really helps you. First of all, when you take some index ([0], [x], n) you have to make sure the element at this index really exists.

I'll leave re-writing your code for your home exercises. It's really important to learn how to solve such little problems all by yourself.

(Another hint: if you want to use "for", calculate count and store it in some local variable before the loop. Again, I hope I don't have to explain why.)

—SA


I fix the problematic code with some changes. This problem often occurs in control collections. I was puzzled by it when trying to remove nodes from a TreeView control.










List<TreeNode> treeList = new List<TreeNode>();
        foreach (TreeNode treeNode in treeViewFolderMove.Nodes)
        {
            treeList.Add(treeNode);
        }
        foreach (TreeNode treeNode in treeList)
        {
            if (treeNode.Value == Value)
            {
                this.treeViewFolderMove.Nodes.Remove(treeNode);
            }
        }


这篇关于如何解决异常:集合被修改;枚举操作可能无法执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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