Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to modify a list in a 'foreach' loop?

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)     } } 

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

like image 369
Polo Avatar asked Apr 17 '09 10:04

Polo


2 Answers

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

As it says on 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.

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

like image 190
Rik Avatar answered Oct 17 '22 12:10

Rik


Make a copy of the enumeration, using an IEnumerable extension method in this case, and enumerate over it. This would add a copy of every element in every inner enumerable to that enumeration.

foreach(var item in Enumerable) {     foreach(var item2 in item.Enumerable.ToList())     {         item.Add(item2)     } } 
like image 30
tvanfosson Avatar answered Oct 17 '22 12:10

tvanfosson