-1

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

  • 4
    Is 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 Answers2

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