Click to See Complete Forum and Search --> : [RESOLVED] foreach skip items


eranga262154
August 13th, 2008, 11:42 PM
hi all,

I want to remove some selected items on a list. So I use a foreach loop.



foreach (int i in MyList.SelectedIndices)
{
MyList.Items.RemoveAt(i);
}


But it remove elements one by one, in odd pattern. Can somebody tell me what's wrong here.

thanks a lot

MNovy
August 14th, 2008, 02:09 AM
foreach is only used for READ-ONLY stuff, as far I know.
You should use a general "for int i" construction to edit any members.

But you have got a simple problem:
By deleting one item of your list, the in indices of the other elements are being reordered and changes so..
if you delete the next item with a selected index now,
you just delete a complete wrong item in your list.

eranga262154
August 14th, 2008, 02:13 AM
Ya, that's true. What I have do there is delete from the last element. Now it's fixed. When I use foreach loop, there is an index conflict take place.

Talikag
August 14th, 2008, 02:50 AM
DO NOT user foreach or for loop if the counter that determines when to exit the loop is changing during the loop.

To solve that problem either use a while loop:

int i=0;
while(i < myList.Items.Count)
{
if(myList.Items[i].ShouldBeRemoved())
myList.Items.RemoveAt(i);
else
i++;
}

(in your case:

while(myList.Items.Count > 0)
{
myList.Items.RemoveAt(0);
}
)
OR a for loop from end to start:

for(i=myList.Count-1;i>=0;i--)
if(myList.Items[i].ShouldBeRemoved())
myList.Items.RemoveAt(i);

(In your case the if statement is not needed)

eranga262154
August 14th, 2008, 03:03 AM
Thanks a lot. I've done it. Thanks for all comments.