在 ForEach 中安全删除 DataRow

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

问题描述

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

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

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

推荐答案

即使 DataRow.Delete 不会修改集合的状态,Microsoft 文档 指出在迭代收藏:

Even though DataRow.Delete doesn't modify the state of the collection, Microsoft documentation states that you shouldn't call it while iterating over the collection:

在遍历 DataRowCollection 对象时,不应在 foreach 循环中调用 Delete 或 Remove.Delete 或 Remove 修改集合的状态.

Neither Delete nor Remove should be called in a foreach loop while iterating through a DataRowCollection object. Delete nor Remove modify the state of the collection.

最好的解决方案通常是为要删除的项目创建一个单独的集合(例如,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.

这也是您想要从集合中删除项目的情况的解决方案,因为 .NET 中的大多数集合不允许您在迭代时更改集合的内容.

This is also the solution for situations where you want to remove items from a collection, as most collections in .NET don't allow you to change the contents of the collection while you're iterating over it.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)