转:关于collection was modified enumeration operation may not execute 错误

http://www.cnblogs.com/nieqq/archive/2010/10/25/1860628.html

今天在使用foreach循环遍历list集合时,出现Collection was modified; enumeration operation may not execute.这个错误,查了半天才发现是当想要修改list集合时,不能使用foreach,因为foreach是取只读的,在取的时候数据不能变(包括修改,删除,添加等),所以要写for循环。

 

 

遍历map(Dictionary)表也会存在这个问题,解决办法就是在foreach搜索到合适的内容和break,然后进行修改。

 

Dictionary<string, user> UserMap;
user theTo;

foreach()

  if()

   user=value;

   break;

user.info=info;

 UserMap[user.key]=user

 

posted @ 2012-04-17 10:20  渡蓝  阅读(318)  评论(0)    收藏  举报