ArrayList behaving badly

  • Thread starter Thread starter Keith O
  • Start date Start date
K

Keith O

Assume fooList is an ArrayList

foreach(string s in fooList) {
if (some condition) {
fooList.Remove(s);
}
}


I get the following runtime error:

An unhandled exception of type 'System.InvalidOperationException' occurred
in mscorlib.dll
Additional information: Collection was modified; enumeration operation may
not execute.


How can I fix this?


Thanks
 
Keith,

you cannot do what you want in this manner.
the foreach statement operates based on the GetEnumerator() reply, and
therefor when you change the content of the arraylist the enumerator is no
longer valid.

try doing it in an other way.

maybe: create a second arraylist for deleted items:

<code>
ArrayList recycleBin = new ArrayList();
foreach (string s in fooList)
{
if (some condition)
{
recycleBin.Add(s);
}
}

foreach (string s in recycleBin)
{
fooList.Remove(s);
}
</code>

HTH
Picho
 
Keith O said:
Assume fooList is an ArrayList
foreach(string s in fooList) {
if (some condition) {
fooList.Remove(s);
}
}

Or you could use a for-loop and traverse the list backwards.

- Michael S
 
You can subvert the read-only characteristics of the foreach construct using
this code

foreach(string s in new System.Collection.ArrayList(fooList)) { //this
opening brace should be on
//the next line by the way
if (some condition) {
fooList.Remove(s);
}
}

Is it a recommended approach? I sincerely doubt it but that's a question for
another thread?

--
Regards,
Alvin Bruney [Microsoft MVP ASP.NET]

[Shameless Author plug]
The Microsoft Office Web Components Black Book with .NET
Now Available @ http://www.lulu.com/owc
 
Back
Top