【发布时间】:2010-10-26 19:49:36
【问题描述】:
根据标题 - C#/.NET 中是否有很好的内置选项可用于 IList 或 IDictionary 上的故障安全迭代?
我遇到问题的地方是类似于以下代码:
IList<Foo> someList = new List<Foo>();
//...
foreach (Foo foo in someList) {
if (foo.Bar) {
someList.remove(foo);
}
}
第一次 foo.Bar 为真后抛出以下内容:
Type: System.InvalidOperationException
Message: Collection was modified; enumeration operation may not execute.
我知道简单的解决方法是使用foreach (Foo foo in new List<Foo>(someList)),但每次都必须记住这样做很烦人。单身的。时间。这出现了。
来自 Java 背景,这可以使用 CopyOnWriteArrayList/ConcurrentHashMap 巧妙地处理(我知道使用这些列表还有其他相关的惩罚。)在 C# 中是否存在我只是没有的等价物知道吗?
【问题讨论】:
-
对于这种特殊情况,
List<T>(但不是IList<T>)有一个RemoveAll(Predicate<T> condition)方法。
标签: c# collections iteration concurrent-collections