c# - 在 'foreach' 循环中修改列表的最佳方法是什么?

标签 c# .net list enumeration enumerable

C#/.NET 4.0 中的一项新功能是您可以在 foreach 中更改您的可枚举对象而不会出现异常。请参阅 Paul Jackson 的博客条目 An Interesting Side-Effect of Concurrency: Removing Items from a Collection While Enumerating 了解有关此更改的信息。

执行以下操作的最佳方法是什么?

foreach(var item in Enumerable)
{
    foreach(var item2 in item.Enumerable)
    {
        item.Add(new item2)
    }
}

通常我使用 IList 作为缓存/缓冲区,直到 foreach 结束,但是有更好的方法吗?

最佳答案

foreach 中使用的集合是不可变的。这在很大程度上是设计使然。

正如它在 MSDN 上所说的那样:

The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.

link 中的帖子Poko 提供的表明这在新的并发集合中是允许的。

关于c# - 在 'foreach' 循环中修改列表的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/759966/

相关文章:

algorithm - 为什么Graph adjacency不定义为邻接集,而是邻接表?

用于连接列表的 Python 列表理解(扁平化)

java - 在列表内迭代列表内的列表java

c# - Entity Framework 一对多关系——外键名称命名为Id时如何重命名?

c# - 如何获取PDF页面的宽度和高度?

c# - XslTransform 与 xml 样式表

.net - 什么是 String.Format 的 WPF XAML 数据绑定(bind)等效项?

c# - 声明式编程和命令式编程有什么区别?

Java LinkedList 上一个 下一个

c# - 类似于 ASP.NET 中的 WCF 服务模拟