什么是修改了“的foreach”循环列表的最佳方法是什么?方法、列表、foreach

2023-09-02 10:15:23 作者:把心掏给你ぢ.

在C#中的一项新功能/ .NET 4.0的是,你可以改变你的的foreach 枚举没有得到例外。见保罗·杰克逊的博客条目的 并发的一个有趣的副作用:删除记录从集合在枚举 的有关此更改的信息。

A new feature in C# / .NET 4.0 is that you can change your enumerable in a foreach without getting the exception. See Paul Jackson's blog entry An Interesting Side-Effect of Concurrency: Removing Items from a Collection While Enumerating for information on this change.

什么是做到以下几点最好的方法是什么?

What is the best way to do the following?

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

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

Usually I use an IList as a cache/buffer until the end of the foreach, but is there better way?

推荐答案

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

The collection used in foreach is immutable. This is very much by design.

由于它说 MSDN :

foreach语句用于   通过集合以获取   你想要的信息,但可以   不能用于添加或删除项目   从源头收集,以避免   联合国predictable副作用。 如果您   需要从添加或删除项目   源收集,使用for循环。

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.

在由波科提供的链接的帖子表明,该允许在新的并发集合。

The post in the link provided by Poko indicates that this is allowed in the new concurrent collections.