C#使用List出现“集合已修改;可能无法执行枚举操作”错误的解决办法
原因:
在循环的时候,当集合被删除了一个item后,那么总数 count和索引就会发生改变.所以会报错
解决方法:
不要在List上执行枚举集合的操作(例如foreach)中去执行修改集合的操作。如果需要修改集合,先使用 ToArray() 方法转化成Array,例如
foreach (string s in rs.ToArray())
{
if (s.IndexOf(t) < 0)
{
rs.Remove(t);
}
}
//处理删除
foreach (var item in oldModel.ShopProductGuiGe.ToArray())
{
if (productGuiGes.Any(q => q.ProductGuiGeValues == item.ProductGuiGeValues) == false)
{
//oldModel.ShopProductGuiGe.Remove(item);
Context.ShopProductGuiGe.Remove(item);
}
}