Help with converting foreach loop to while loop in c#

Posted by James Dawson on Stack Overflow See other posts from Stack Overflow or by James Dawson
Published on 2010-03-24T06:42:43Z Indexed on 2010/03/24 6:43 UTC
Read the original article Hit count: 619

Filed under:
|
|

I had learnt by reading your great answers here, that it is not good practice deleting items from within a foreach loop, as it is (and I quote) "Sawing off the branch you're sitting on".

My code currently removes the text from the dropdownlist, but the actual item remains (just without text displayed).

In other words, it isn't deleting, and probably can't because you can't delete from within a foreach loop.

After hours of trying I am unable to get my head around a way of doing it.

//For each checked box, run the delete code
for (int i = 0; i < this.organizeFav.CheckedItems.Count; i++)
        {

//this is the foreach loop
            foreach (ToolStripItem mItem in favoritesToolStripMenuItem.DropDownItems)
            {

                //This rules out seperators
                if (mItem is ToolStripMenuItem)
                {
                    ToolStripMenuItem menuItem = mItem as ToolStripMenuItem;

             //This matches the dropdownitems text to the CheckedItems String
                    if (((ToolStripMenuItem)mItem).Text.ToString() == organizeFav.CheckedItems[i].ToString())
                    {
                         //And deletes the item
                        menuItem.DropDownItems.Remove(mItem);
                    }
                }
            }
        }

But it isn't deleting because it is within a foreach loop! I would greatly appreciate your help, and be truly amazed if anyone can get their head around this code :)

Kind Regards

© Stack Overflow or respective owner

Related posts about c#

Related posts about foreach