|
-
August 13th, 2008, 11:42 PM
#1
[RESOLVED] foreach skip items
hi all,
I want to remove some selected items on a list. So I use a foreach loop.
Code:
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
-
August 14th, 2008, 02:09 AM
#2
Re: foreach skip items
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.
-
August 14th, 2008, 02:13 AM
#3
Re: foreach skip items
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.
-
August 14th, 2008, 02:50 AM
#4
Re: foreach skip items
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:
Code:
int i=0;
while(i < myList.Items.Count)
{
if(myList.Items[i].ShouldBeRemoved())
myList.Items.RemoveAt(i);
else
i++;
}
(in your case:
Code:
while(myList.Items.Count > 0)
{
myList.Items.RemoveAt(0);
}
)
OR a for loop from end to start:
Code:
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)
Last edited by Talikag; August 14th, 2008 at 02:52 AM.
-
August 14th, 2008, 03:03 AM
#5
Re: foreach skip items
Thanks a lot. I've done it. Thanks for all comments.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|