CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Sep 2007
    Posts
    85

    [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

  2. #2
    Join Date
    Jul 2008
    Location
    Germany
    Posts
    210

    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.

  3. #3
    Join Date
    Sep 2007
    Posts
    85

    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.

  4. #4
    Join Date
    Jan 2007
    Posts
    491

    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.

  5. #5
    Join Date
    Sep 2007
    Posts
    85

    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
  •  





Click Here to Expand Forum to Full Width

Featured