安全地删除DataRow在ForEach [英] Safely Removing DataRow In ForEach

查看:137
本文介绍了安全地删除DataRow在ForEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么这段代码不起作用。

I don't understand why this code does not work.

foreach (DataRow dataRow in dataTable.Rows)
{
    if (true)
    {
        dataRow.Delete();
    }
}


推荐答案

.NET中的集合不允许您在迭代时更改集合的内容。从文档 IEnumerator

Most collections in .NET don't allow you to change the contents of the collection while you're iterating over it. From the docs for IEnumerator:


只要
,枚举器仍然有效,集合保持不变。如果
更改为集合,
,如添加,修改或删除
元素,枚举器是
不可恢复地无效,下一个
调用MoveNext或重置抛出
InvalidOperationException。如果
集合在
MoveNext和Current之间被修改,Current将返回
它被设置为的元素,即使
枚举器已经无效。

An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or Reset throws an InvalidOperationException. If the collection is modified between MoveNext and Current, Current returns the element that it is set to, even if the enumerator is already invalidated.

最好的解决方案通常是创建一个单独的集合(例如 List< DataRow> )项目您要删除,然后在完成迭代后将其移除

The best solution is usually to create a separate collection (e.g. a List<DataRow>) of items you want to remove, and then remove them after you've finished iterating.

这篇关于安全地删除DataRow在ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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