Remove items from ArrayList

C

Curious

Hi,

I have an array list in which some items are marked as "ShouldRemove".
When I loop through each item, I should remove these items. However, I
believe that I will get "Collection was modified; enumeration
operation may not execute" error.

foreach (BenchmarkPrice bp in mBenchmarkPriceList)
{
if (bp.ShouldRemove == true)
{
// This won't work because this alters the length
of the array list, mBenchmarkPriceList
mBenchmarkPriceList.Remove (bp);
}
}

Any advice on how to get this done safely?
 
J

Jack Jackson

Hi,

I have an array list in which some items are marked as "ShouldRemove".
When I loop through each item, I should remove these items. However, I
believe that I will get "Collection was modified; enumeration
operation may not execute" error.

foreach (BenchmarkPrice bp in mBenchmarkPriceList)
{
if (bp.ShouldRemove == true)
{
// This won't work because this alters the length
of the array list, mBenchmarkPriceList
mBenchmarkPriceList.Remove (bp);
}
}

Any advice on how to get this done safely?

Don't use an enumeration. Instead of For Each, use a loop from the
end to the beginning:

For indx As Integer = mBenchmarkPriceList.Count - 1 TO 1 STEP -1
Dim bp As BenchMarkPrice = mBenchmarkPriceList(indx)
...
 

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