C#错误集合已修改;枚举操作可能无法执行 [英] C# error Collection was modified; enumeration operation might not execute

查看:81
本文介绍了C#错误集合已修改;枚举操作可能无法执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我正在调用的代码,并且正在发生异常.集合已修改;枚举操作可能无法执行.

Below is my code which am calling and am getting below exception. Collection was modified; enumeration operation might not execute.

在此代码中,检查数据集是否包含tb_error表名称,然后检查行数.如果rowcount> 1,则插入db.之后,我想清除该表,然后再清除其他视图.请帮助我在哪里修改我的代码.

In this code am checking if dataset contains tb_error table name and then checking the row count. If rowcount> 1 , insert into db. after that i want to clear that table and after that i need to clear other view also. Please help me where to modify my code.

    if (MainClass.OutputDataset.Tables.Contains(tb_error.TableName))
         {
             foreach (DataRow drErr in MainClass.OutputDataset.Tables[tb_error.TableName].Rows)
             {
                 //insert into DB
             }
         }

        if (MainClass.OutputDataset != null && MainClass.OutputDataset.Tables["tb_error"].Rows.Count > 0)
        {
            MainClass.OutputDataset.Tables["tb_error"].Clear();
        }

        MainClass.dsinput.Tables.Remove("BSData_VW");               
        }

推荐答案

之所以会发生这种情况,是因为此基础集合已经添加或删除了项,从而使循环无效.

This happens because the underlying collection has since had items added or removed, which invalidates the loop.

您可以通过拍摄快照来解决此问题,例如:

You can get around this by taking a snapshot, e.g.:

foreach (DataRow drErr in MainClass.OutputDataset.Tables[tb_error.TableName].Rows.ToList())
{
   //insert into DB
}

关键是最后一个 .ToList()调用,这意味着foreach循环仅在时间点上对 Rows 进行操作.

The key is the .ToList() call at the end, which means the foreach loop only operates on Rows as it is at the point-in-time.

这篇关于C#错误集合已修改;枚举操作可能无法执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆