I always get the collection was modified error when adding elements to List<> while it is being used in for i or foreach loops and it makes cross threading a little bit complicated. Is there a special class I'm missing that will not make the enumerator invalid if the collection is modified?
Asked
Active
Viewed 89 times
0
-
1. for loops should not give you this error ...? 2. if you need to modify the collection while looping, maybe create a new collection? – McGarnagle Jun 16 '13 at 01:09
-
Have you tried creating a temporary List of the items to add and then just add them after the foreach loop ? – jamauss Jun 16 '13 at 01:09
-
you can use the method `.ToList()` to avoid that error.. `foreach(var x in l.ToList())` – spajce Jun 16 '13 at 01:11
-
Cross threading? Are adding to a List
while enumerating it in another thread? You do realize that a List – shf301 Jun 16 '13 at 01:12is not thread safe. Maybe what you want is one of the concurrent collections. http://msdn.microsoft.com/en-us/library/dd287108.aspx
2 Answers
3
If you are trying to add or remove items from the collection you are looping from then you will receive a InvalidOperationException
.
To avoid that you need to either create and iterate over a copy of the array/list you are currently iterating from or create a temporary list to host the changes you are making then use that one to update your original source.

coolmine
- 4,427
- 2
- 33
- 45
-
I loop through them on one thread and modify them on the other thus the exception is thrown, is there any way I can catch it and restart the loop on the remaining items? How would such a custom class look? – user2489890 Jun 16 '13 at 01:35
-
Update the question with some code to make it a bit easier to help you out. Hard to say without seeing how you modify the list. – coolmine Jun 16 '13 at 01:36
-
I really don't have anything currently nor do I have any idea of how to approach it, I am surprised no one has developed a collection-was-modified-resistant List<> it sounds rather simple in my head, just store another List of all the elements we've already looped through and if we catch this error we start all over again ignoring the "previously looped through" list. – user2489890 Jun 16 '13 at 01:58
-
Then the framework would be duplicating the list without allowing for other options. The current system gives you the option to duplicate it yourself or simply use other techniques such as the ones I mentioned or simply iterating over a list backwards. It is actually quite simple in most cases. Take a look at the answer at http://stackoverflow.com/a/604843/1630928 – coolmine Jun 16 '13 at 03:06
1
As far as removing (deleting) item from a collection goes, you can also iterate over a copy of a collection backwards and delete the items as you need to and this will not cause trouble because it will not negatively impact the index of the items remaining to be iterated.

Karl Anderson
- 34,606
- 12
- 65
- 80