ArrayList behaving badly

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
 
P

Picho

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
 
M

Michael S

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
 
A

Alvin Bruney [MVP]

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top