Introduction
I happen to edit the collections many times in the foreach loop and run into problems and then each time I got a different solution when going to Google, So first I would try to list each of the solution and then discuss them so that we all can have the best practice in the collection iteration. Please note that I am not saying the one I have mentioned is the best but I found it to be one of the best for my context.
Background
Recently I cam across an exception as Collection was modified; enumeration operation may not execute. and the sample code which can throw such exception is
Code: CSharp
ArrayList list = new ArrayList();
list.Add("123");
list.Add("456");
list.Add("789");
list.Add("741");
list.Add("852");
foreach (string s in list)
{
if (s == "789")
{
list.RemoveAt(list.IndexOf("789"));
}
}
Solution 1 : Convert collection to Array
Code: CSharp
foreach (string s in list.ToArray())
{
if (s == "789")
{
list.RemoveAt(list.IndexOf("789"));
}
}
Solution 2 : Use for loop instead foreach.
Code: CSharp
int cnt = list.Count - 1;
for (int i = 0; i < cnt; )
{
string s = (string)list[i];
System.Console.WriteLine(s);
if (s == "789")
{
list.RemoveAt(i);
}
else
{
i++;
}
}
Solution 3 : Mark all the element.
Mark all the elements you wish to remove and then iterate through the marked object to remove them.
Code: CSharp
ArrayList indexListToRemove = new ArrayList();
foreach (string s in list)
{
if (s == "789")
{
indexListToRemove.Add(s);
}
}
foreach (string s in indexListToRemove)
{
list.Remove(s);
}
Summary
You should avoid changes to collections (in fact most cases you will not even be able to change the collection) using foreach.

