when i tried to remove element from the list collection using foreach im getting enumeration exception .i searched in net but im not getting proper explanation for the problem . if anyone knows about this share the information
Asked
Active
Viewed 53 times
-1
-
4Is this java, javascript, or C#? Please edit your tags to only include the relevant languages. Please also read [ask], and include a [mcve] – canton7 Jan 29 '21 at 15:25
-
check this out https://stackoverflow.com/questions/4004755/why-is-foreach-loop-read-only-in-c-sharp – Benzara Tahar Jan 29 '21 at 15:42
2 Answers
-1
You can't remove an item from the same ICollection which foreach is currently running on. If you want to remove items from same collection while inside a loop, use a secondary list
//Define a secondary variable
var items = new List<string>{"One", "Two", "Three", "Four"};
var secondaryList = new List<string>(items);
//Now iterate and remove according you want from second variable
foreach(var i in items)
{
if(i=="Two") { secondaryList.remove(i) }
}
//Once iteration is over, copy back
items = new List<string>(secondaryList);

Sangeeth Nandakumar
- 1,362
- 1
- 12
- 23
-
secondaryList references the same collection! how does this really work? – Benzara Tahar Jan 29 '21 at 15:32
-
Secondary list should not be a reference to previous variable. It should be a different variable with copied contents only. – Sangeeth Nandakumar Jan 29 '21 at 15:34
-
-
This will not work, you might have wanted to do var secondaryList = new List
(items); and in the last step items = new List – Alexandru Clonțea Jan 29 '21 at 18:03(secondaryList). -
Exactly, I've modified the code for any future people to refer. Thanks @AlexandruClonțea – Sangeeth Nandakumar Jan 29 '21 at 18:12
-1
Yes, previous posters are correct. One should not remove items from a collection one is iterating over. It may invalidate the iterator. First determine which items you need to remove, then iterate over that list to remove the items from the original collection. Something like this:
IList<int> myCollection = new List<int> { 1, 2, 3, 4, 5, 6 };
IList<int> itemsToRemove = new List<int>();
foreach(var item in myCollection)
{
if (item % 2 == 0)
{
itemsToRemove.Add(item);
}
}
foreach(var toRemove in itemsToRemove)
{
myCollection.Remove(item);
}

Natalia Muray
- 252
- 1
- 6