帮助“集合已修改;枚举操作可能无法执行。”
当我使用以下代码时,出现“集合已修改;枚举操作可能无法执行”错误。如果我理解正确,我认为这意味着我无法枚举该数据表并同时从中删除行。我的问题是,我还能做什么来实现从数据表中删除某些行的结果? 这是我的代码:
// Now let's loop through the datatable and find any account with no
// LYSMKWh value and less than 4000 KWh current usage. We'll remove those
// from the datatable.
currentRow = 0;
foreach (DataRow row in resultsDT.Rows)
{
if ((string)resultsDT.Rows[currentRow]["LYSMKWh"] == "0")
{
int intKWh = Convert.ToInt32(resultsDT.Rows[currentRow]["KWH"]);
if (intKWh < 5000)
{
resultsDT.Rows[currentRow].Delete();
}
}
resultsDT.AcceptChanges();
currentRow++;
}
When I use the following code, I'm getting a "Collection was modified; enumeration operation might not execute" error. If I understand this correctly, I think it means that I can't enumerate over this datatable and delete rows from it at the same time. My question is, what else can I do to achieve the result of deleting certain rows from my datatable?
Here's my code:
// Now let's loop through the datatable and find any account with no
// LYSMKWh value and less than 4000 KWh current usage. We'll remove those
// from the datatable.
currentRow = 0;
foreach (DataRow row in resultsDT.Rows)
{
if ((string)resultsDT.Rows[currentRow]["LYSMKWh"] == "0")
{
int intKWh = Convert.ToInt32(resultsDT.Rows[currentRow]["KWH"]);
if (intKWh < 5000)
{
resultsDT.Rows[currentRow].Delete();
}
}
resultsDT.AcceptChanges();
currentRow++;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以执行以下两种操作之一:
1) 您可以使用 for 循环以相反的顺序迭代集合并删除内联的行:
2) 您可以将要删除的行添加到单独的集合中,然后在删除后删除它们迭代整个原始集合。这显然效率较低,所以我不会担心样本。
You can do one of two things:
1) You can iterate over the collection in reverse order using a for loop and remove the rows inline:
2) You can add the rows you want to remove to a separate collection and then remove them after you iterate over the entire original collection. This is obviously less efficient so I'm not going to worry about a sample.