在“foreach"循环中修改列表的最佳方法是什么? [英] What is the best way to modify a list in a 'foreach' loop?

查看:37
本文介绍了在“foreach"循环中修改列表的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#/.NET 4.0 中的一个新功能是您可以在 foreach 中更改可枚举项而不会出现异常.请参阅 Paul Jackson 的博客条目 并发的一个有趣的副作用:在枚举时从集合中删除项目 了解有关此更改的信息.

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 语句用于遍历集合以获得您想要的信息,但可以不可用于添加或删除项目从源头收集避免不可预测的副作用.如果你需要添加或删除项目源集合,使用 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.

链接中的帖子提供by Poko 表示这在新的并发集合中是允许的.

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

这篇关于在“foreach"循环中修改列表的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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