一、问题描述

  在做 数组、列表、集合遍历时,可能我们会遇见这个问题。Collection was modified;enumeration operation may not execute ,翻译的中文意思:集合已修改;枚举操作可能无法执行。

二、解决方案

  就是在遍历时,不要改变正在遍历的集合即可,您可以先遍历完在对其进行操作。

三、案例

  出现问题前的代码如下,就是我在遍历 items 的同时,又往 items 中 add 数据。

  1. public async Task<ListResultDto<RecordBookListDto>> GetFlatRecordBookItems()
  2. {
  3. var query = _recordBookRepository
  4. .GetAll();
  5. var entities = await query.ToListAsync();
  6. var items = new List<RecordBookListDto>();
  7. foreach (var entity in entities)
  8. {
  9. var dto = entity.MapTo<RecordBookListDto>();
  10. items.Add(dto);
  11. }
  12.  
  13. //todo 获取测点编号
  14. foreach (var item in items)
  15. {
  16. if (!string.IsNullOrEmpty(item.DataId))
  17. {
  18. String[] array = item.DataId.Replace("[", "").Replace("]", "").Replace("\"", "").Split(',');
  19.  
  20. foreach (var ar in array)
  21. {
  22. var ins = _instrumentGroupRepository.Get(Guid.Parse(ar));
  23. var l = new RecordBookListDto();
  24. l.Id = Guid.Parse(ar);
  25. l.ParentId = item.Id.ToString();
  26. l.Name = ins.No;
  27. items.Add(l);
  28. }
  29. }
  30. }
  31.  
  32. var listDto = new ListResultDto<RecordBookListDto>(items);
  33. return listDto;
  34. }

  修改完成后的代码:

  1. public async Task<ListResultDto<RecordBookListDto>> GetFlatRecordBookItems()
  2. {
  3. var query = _recordBookRepository
  4. .GetAll();
  5. var entities = await query.ToListAsync();
  6. var items = new List<RecordBookListDto>();
  7. foreach (var entity in entities)
  8. {
  9. var dto = entity.MapTo<RecordBookListDto>();
  10. items.Add(dto);
  11. }
  12.  
  13. List<RecordBookListDto> newItems = new List<RecordBookListDto>();
  14.  
  15. //todo 获取测点编号
  16. foreach (var item in items)
  17. {
  18. if (!string.IsNullOrEmpty(item.DataId))
  19. {
  20. String[] array = item.DataId.Replace("[", "").Replace("]", "").Replace("\"", "").Split(',');
  21.  
  22. foreach (var ar in array)
  23. {
  24. var ins = _instrumentGroupRepository.Get(Guid.Parse(ar));
  25. var l = new RecordBookListDto();
  26. l.Id = Guid.Parse(ar);
  27. l.ParentId = item.Id.ToString();
  28. l.Name = ins.No;
  29. newItems.Add(l);
  30. }
  31. }
  32. }
  33.  
  34. foreach (var item in newItems)
  35. {
  36. items.Add(item);
  37. }
  38.  
  39. var listDto = new ListResultDto<RecordBookListDto>(items);
  40. return listDto;

C# Collection was modified;enumeration operation may not execute的更多相关文章

  1. List使用Foreach 修改集合时,会报错的解决方案 (Error: Collection was modified; enumeration operation may not execute. ) - 摘自网络

    当用foreach遍历Collection时,如果对Collection有Add或者Remove操作时,会发生以下运行时错误: "Collection was modified; enume ...

  2. 解决Collection was modified; enumeration operation may not execute异常

    今天在使用foreach循环遍历list集合时,出现Collection was modified; enumeration operation may not execute.这个错误,查了半天才发 ...

  3. Collection was modified; enumeration operation may not execute.的异常处理

    Collection was modified; enumeration operation may not execute.的异常处理 在运行程序时遇到这样一段异常,仔细检查后发现是使用Foreac ...

  4. Error: Collection was modified; enumeration operation may not execute.

    http://blog.csdn.net/ffeiffei/article/details/6131254

  5. Collection was modified; enumeration operation may not execute Dictionary 集合已修改;可能无法执行枚举操作

    public void ForeachDic() { Dictionary dic = new Dictionary(); dic.Add("1", 10); dic.Add(&q ...

  6. 关于struts2的checkboxlist、select等标签发生could not be resolved as a collection/array/map/enumeration/iterator type异常的记录

    1 刚进入该界面的时候发生错误,原因是 list="roles"中的这个集合是空的,导致错误 解决办法很简单,不能让list为空 2 刚进入该界面的时候list是有数据的,当点击提 ...

  7. 做WP程序时遇到的一些问题及解决方法

    问题1:Type 'JDBYSJ.Data.NewsChannel' cannot be serialized. Consider marking it with the DataContractAt ...

  8. C# 使用Linq递归查询数据库遇到的问题及解决方法

    User表通常是我们在写"XX管理系统"项目时必须要用到的,有的情况下人员的分类属于树形结构,就是除了最高层和最低层,中间层都有相对的父和子,设计数据库的时候,我们通常会加一个pa ...

  9. C#在foreach循环中修改字典等集合出错的处理

    C#在foreach循环中修改字典等集合出错:System.InvalidOperationException: Collection was modified; enumeration operat ...

随机推荐

  1. HDU 4714 Tree2cycle:贪心

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4714 题意: 给你一棵树,添加和删除一条边的代价都是1.问你将这棵树变成一个环的最小代价. 题解: 贪 ...

  2. HDU 4336 Card Collector:期望dp + 状压

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4336 题意: 一共有n种卡片.每买一袋零食,有可能赠送一张卡片,也可能没有. 每一种卡片赠送的概率为p ...

  3. MVC中ajax调用Controller的方法

    1. ajax代码: $.ajax({ async: false, cache: false, type: 'POST', contentType: "application/json&qu ...

  4. 分享知识-快乐自己:Shiro 退出登陆清空缓存实现

    shiro是一个被广泛使用的安全层框架,通过xml配置方式与spring无缝对接,用户的登陆/退出/权限控制/Cookie等管理系统基础功能交给shiro来管理. 一般,在JavaWEB管理平台系统时 ...

  5. python中的排序函数

    1.sort() list类型有一个自带的排序函数sort() list.sort(cmp=None, key=None, reverse=False) 参数说明: (1)  cmp参数 cmp接受一 ...

  6. stl_queue.h

    stl_queue.h // Filename: stl_queue.h // Comment By: 凝霜 // E-mail: mdl2009@vip.qq.com // Blog: http:/ ...

  7. Spring MVC表单提交

    实际应用中,列表中的单条记录的修改,可能需要传很多对象参数到后台服务器,Spring MVC表单标签<form:> 提供了一种简洁的提交方式. <form id="form ...

  8. java多线程编程核心技术——第三章总结

    第一节等待/通知机制 1.1不使用等待/通知机制实现线程间的通讯 1.2什么是等待/通知机制 1.3等待/通知机制的实现 1.4方法wait()锁释放与notify()锁不释放 1.5当interru ...

  9. sysbench安装、使用

    二.编译安装 编译非常简单,可参考 README 文档,简单步骤如下:   cd/tmp/sysbench-0.4.12-1.1./autogen.sh./configure --with-mysql ...

  10. influxdb api

    https://influxdb-python.readthedocs.io/en/latest/examples.html