当用foreach遍历Collection时,如果对Collection有Add或者Remove操作时,会发生以下运行时错误: "Collection was modified; enumeration operation may not execute." 如下所示: [c-sharp] view plaincopy List<string> list = new List<string>(); for (int i = 0; i < 10; i++)…
今天在使用foreach循环遍历list集合时,出现Collection was modified; enumeration operation may not execute.这个错误,查了半天才发现是当想要修改list集合时,不能使用foreach,因为foreach是取只读的,在取的时候数据不能变(包括修改,删除,添加等),所以只能用for循环.…
一.问题描述 在做 数组.列表.集合遍历时,可能我们会遇见这个问题.Collection was modified;enumeration operation may not execute ,翻译的中文意思:集合已修改:枚举操作可能无法执行. 二.解决方案 就是在遍历时,不要改变正在遍历的集合即可,您可以先遍历完在对其进行操作. 三.案例 出现问题前的代码如下,就是我在遍历 items 的同时,又往 items 中 add 数据. public async Task<ListResultDto…
Collection was modified; enumeration operation may not execute.的异常处理 在运行程序时遇到这样一段异常,仔细检查后发现是使用Foreach...In语法体内运用了对Collection的Remove或Add导致的,只需要将foreach方法改为for方法即可. for (int i = 0; i < this.prtdeallist.Items.Count; i++) { RepeaterItem repeaterItem = th…
http://blog.csdn.net/ffeiffei/article/details/6131254…
public void ForeachDic() { Dictionary dic = new Dictionary(); dic.Add("1", 10); dic.Add("2", 20); dic.Add("3", 30); foreach (KeyValuePair kvp in dic) { Console.WriteLine(String.Format("Key:{0}; Value:{1}", kvp.Key,…
1 刚进入该界面的时候发生错误,原因是 list="roles"中的这个集合是空的,导致错误 解决办法很简单,不能让list为空 2 刚进入该界面的时候list是有数据的,当点击提交等按钮的时候,数据被提交到后台,如果配置了验证框架或者在action中写了validate方法,校验没有通过,未走action,直接返回了input,又指定回了当前界面.此时的checkboxlist中的list丢失了,导致了如上错误(这个错误提示的不太友好,让人认为是类转换错误) 解决办法是把初始化lis…
问题1:Type 'JDBYSJ.Data.NewsChannel' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the t…
User表通常是我们在写"XX管理系统"项目时必须要用到的,有的情况下人员的分类属于树形结构,就是除了最高层和最低层,中间层都有相对的父和子,设计数据库的时候,我们通常会加一个parent_id这样的字段.这样我们就可以通过当前用户的user_id查询出他的直接下属有哪些,或者通过parent_id查询出他的直接上司是谁. 但是当我们想通过user_id去查询出其所有下属的时候,就不是能用一条简单的sql能实现的了.如果项目要是.Net Framework3.5以下的,就是没有Linq…
C#在foreach循环中修改字典等集合出错:System.InvalidOperationException: Collection was modified; enumeration operation may not execute.这是因为在foreach中不允许修改集合,可通过如下方式修改dictPublish的值,如: Dictionary<string, string> _dict = new Dictionary<string, string>(dictPublis…