在 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];

   ///具体业务代码

}

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

猜你喜欢

转载自www.cnblogs.com/llw1996/p/12825716.html
今日推荐