日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

C# Collection was modified;enumeration operation may not execute

發布時間:2025/3/8 60 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C# Collection was modified;enumeration operation may not execute 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、問題描述

  在做 數組、列表、集合遍歷時,可能我們會遇見這個問題。Collection was modified;enumeration operation may not execute ,翻譯的中文意思:集合已修改;枚舉操作可能無法執行。

二、解決方案

  就是在遍歷時,不要改變正在遍歷的集合即可,您可以先遍歷完在對其進行操作。

三、案例

  出現問題前的代碼如下,就是我在遍歷 items 的同時,又往 items 中 add 數據。

public async Task<ListResultDto<RecordBookListDto>> GetFlatRecordBookItems(){var query = _recordBookRepository.GetAll();var entities = await query.ToListAsync();var items = new List<RecordBookListDto>();foreach (var entity in entities){var dto = entity.MapTo<RecordBookListDto>();items.Add(dto);}//todo 獲取測點編號foreach (var item in items){if (!string.IsNullOrEmpty(item.DataId)){String[] array = item.DataId.Replace("[", "").Replace("]", "").Replace("\"", "").Split(',');foreach (var ar in array){var ins = _instrumentGroupRepository.Get(Guid.Parse(ar));var l = new RecordBookListDto();l.Id = Guid.Parse(ar);l.ParentId = item.Id.ToString();l.Name = ins.No;items.Add(l);}}}var listDto = new ListResultDto<RecordBookListDto>(items);return listDto;}

  修改完成后的代碼:

public async Task<ListResultDto<RecordBookListDto>> GetFlatRecordBookItems(){var query = _recordBookRepository.GetAll();var entities = await query.ToListAsync();var items = new List<RecordBookListDto>();foreach (var entity in entities){var dto = entity.MapTo<RecordBookListDto>();items.Add(dto);}List<RecordBookListDto> newItems = new List<RecordBookListDto>();//todo 獲取測點編號foreach (var item in items){if (!string.IsNullOrEmpty(item.DataId)){String[] array = item.DataId.Replace("[", "").Replace("]", "").Replace("\"", "").Split(',');foreach (var ar in array){var ins = _instrumentGroupRepository.Get(Guid.Parse(ar));var l = new RecordBookListDto();l.Id = Guid.Parse(ar);l.ParentId = item.Id.ToString();l.Name = ins.No;newItems.Add(l);}}}foreach (var item in newItems){items.Add(item);}var listDto = new ListResultDto<RecordBookListDto>(items);return listDto;

?

轉載于:https://www.cnblogs.com/gzbit-zxx/p/10762215.html

總結

以上是生活随笔為你收集整理的C# Collection was modified;enumeration operation may not execute的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。