For each loop does not work when removing items from a list

why can't I use foreach loop to remove items from a list:

   
 protected void btnRemove_Click(object sender, EventArgs e)
        {
            ListBox listbox = Controltest2.FindControl("ListBox1") as ListBox;
            if (Controltest2.Items.Count > 0)
            {
                foreach (ListItem li in listbox.Items)
                {
                    if (li.Selected)
                    {
                        Controltest2.Remove(li.Value);
                    }
                }
            }
        }

These codes give me an error to remove an item from the list. On the other hand,

   ListBox listbox = Controltest2.FindControl("ListBox1") as ListBox;
            if (Controltest2.Items.Count > 0)
            {
                int count = Controltest2.Items.Count;
                for (int i = count - 1; i > -1; i--)
                {
                    if (listbox.Items[i].Selected)
                    {
                        Controltest2.Remove(listbox.Items[i].Value);
                    }
                }
            }

Why can't I use the "Foreach loop" instead of the "for loop" ...
+5
source share
4 answers

The foreach statement repeats a group of inline statements for each element of an array or collection of objects. The foreach statement is used to iterate through the collection to obtain the desired information , but should not be used to modify the contents of the collection to avoid unpredictable side effects.

Source: MSDN foreach

:

+14

foreach, , , . foreach, :

foreach (ListItem li in listbox.Items.ToArray())
{
    if (li.Selected)
    {
        Controltest2.Remove(li.Value);
    }
}

: ToArray() , LINQ Cast<T>() . , , , , , foreach ListBox, ListBox .

+6

: , foreach, ,

+2

In the first example, you delete items from the start of the collection, which affects the collection that defines the iteration conditions, while in the second case, you remove items from the end of the collection each time, and the initial conditions of the loop are not affected due to the fixed value of int count.

0
source

All Articles