简体   繁体   English

从ListBox中删除项目时,每个循环不起作用

[英]For Each Loop Not Working When Removing Items From ListBox

why can not i use foreach loop to drop items from listbox: 为什么我不能使用foreach循环从列表框中删除项目:

   
 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);
                    }
                }
            }
        }

This codes give me error to drop item from listbox. 此代码使我从列表框中删除项目时出错。 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 cannot i use "Foreach loop" instead of "for loop"... 为什么我不能使用“Foreach循环”而不是“for循环”......

The foreach statement repeats a group of embedded statements for each element in an array or an object collection. foreach语句为数组或对象集合中的每个元素重复一组嵌入式语句。 The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects foreach语句用于迭代集合以获取所需信息, 但不应用于更改集合的内容以避免不可预测的副作用

Source: MSDN foreach 资料来源:MSDN foreach

Note: emphasis mine 注意:强调我的

When you use the foreach loop, you are modifying the underlying collection, thereby interupting the enumerator so to speak. 当你使用foreach循环时,你正在修改底层集合,从而可以说出中断枚举器。 If you want to use the foreach loop, try the following: 如果要使用foreach循环,请尝试以下操作:

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

Note: the call to ToArray() in this example assumes LINQ to object and depending on the situation, you may be required to also call the Cast<T>() prior to calling it. 注意:在此示例中对ToArray()的调用假定LINQ为对象,并且根据情况,您可能还需要在调用之前调用Cast<T>() The main point that I am trying to get across here is that by creating an array, the foreach is now iterating over the array's enumerator instead of the ListBox's enumerator, allowing you to modify the ListBox's collection at will. 我试图在这里得到的主要观点是,通过创建一个数组,foreach现在迭代数组的枚举器而不是ListBox的枚举器,允许您随意修改ListBox的集合。

简短回答:使用foreach迭代循环时,无法添加或删除循环的项目

在第一个示例中,您将从集合的开头删除项目,这会影响定义迭代条件的集合,而在第二种情况下,您每次都会从集合的末尾删除项目,并且由于int count的固定值,循环初始条件不受影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM