Iterating a collection and removing item

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How can I iterate a collection and conditionally remove items from the
collection using either C# or VB.NET?

When I try to remove an item, I get the error message that I am not allowed
to remove an item.

Thanks
 
Instead of using a For Each (foreach in C#) loop, iterate over the
collection using an index and *make sure* to start from the bottom up.

For i As Integer = myCollection.Count - 1 To 0
If something Then
myCollection.Remove(i)
End If
Next i

for(int i = myCollection.Count - 1; i>=0; i--)
{
If(something)
{
myCollection.RemoveAt(i);
}
}

I'm sure you see why I stressed on starting from the bottom :)

hope that helps..
Imran.
 
Instead of using a For Each (foreach in C#) loop, iterate over the
collection using an index and *make sure* to start from the bottom up.

For i As Integer = myCollection.Count - 1 To 0

Don't you need a Step -1 on the end of this line?

--
Chris

dunawayc[AT]sbcglobal_lunchmeat_[DOT]net

To send me an E-mail, remove the "[", "]", underscores ,lunchmeat, and
replace certain words in my E-Mail address.
 
This is currently how I am doing it (reverse loop) . I was hoping that there
was a different method to do it.

Thanks.
 
Back
Top