在 foreach 中操作集合时报错:Collection was modified; enumeration operation may not execute.

错误信息:System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

在foreach操作集合时候可能会遇到这个提示

原: 

foreach (var stockEnterItem in stockEnter.List_StockEnterItems)
{   //具体业务代码  }

如果出现如标题中的错误,则需要将 foreach 修改为 for。下面是修改为 foreach 为 for 后的逻辑。

var stockEnterItems = stockEnter.List_StockEnterItems;
var keys = new List<StockEnterItems>(stockEnterItems);
for (int i = 0; i < keys.Count; i++)
{
  var key = keys[i];

   ///具体业务代码

}

 

这样就可以顺利操作集合了。原因是引用类型内存地址指向同一内存地址导致的。

posted @ 2020-05-04 10:59  lusCodding  阅读(625)  评论(0编辑  收藏  举报