Remove items from ArrayList

  • Thread starter Thread starter Curious
  • Start date Start date
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?
 
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)
...
 
Back
Top