By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,320 Members | 1,893 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,320 IT Pros & Developers. It's quick & easy.

Iterating a collection and removing item

P: n/a

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
Jul 21 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
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.

"STech" <ST***@discussions.microsoft.com> wrote in message
news:05**********************************@microsof t.com...

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

Jul 21 '05 #2

P: n/a
On Wed, 13 Oct 2004 23:06:01 -0400, Imran Koradia wrote:
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.
Jul 21 '05 #3

P: n/a
>> For i As Integer = myCollection.Count - 1 To 0

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


duh! thats right. my apologies :(
Jul 21 '05 #4

P: n/a
This is currently how I am doing it (reverse loop) . I was hoping that there
was a different method to do it.

Thanks.

"Imran Koradia" wrote:
For i As Integer = myCollection.Count - 1 To 0


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


duh! thats right. my apologies :(

Jul 21 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.