首页 > 解决方案 > C# foreach 和列表框删除项目

问题描述

我对操作员 Foreach 有疑问,我用它来获取匹配项并将它们放在其他列表框中。问题是我需要从文件中获取所有匹配项,并将它们放在 listbox2 或 3 中。但从 listbox1 中只需要删除项目(0)。

现在,如果文件中的匹配项是 5、6、7 等,它将把它们都放在 listbox2 或 3 中,但它也会从 listbox1 中删除 5、6、7 等项目。我只需要从 listbox1 中删除一次 item(0)。这是代码。谢谢!

foreach (Match match in matches)
{
    if (matches.Count > 0)
    // if (match.Success)
    {
        label6.Text = "found!";
        listBox2.Items.Add(searchemailKOK + "|" + match);
        progressBar1.Increment(1);
        pictureBox3.Height = (200 - (progressBar1.Value / 2));
        label1.Text = listBox1.Items.Count.ToString();
        label2.Text = listBox2.Items.Count.ToString();
        timer2.Start();
        if (listBox1.Items.Count > 0)
        {
            listBox1.Items.RemoveAt(0); 
        }
        timer1.Stop();
     }
 } 

标签: c#listbox

解决方案


您不能使用 foreach 循环从列表中删除项目,因为它会更改当前正在操作的列表的结构。因此将抛出异常。

你可以使用 for 循环,但你需要反向使用它

for(int = list.count-1; i >= 0; i--)
{
    if(list[i].id == 5)
       list.RemoveAt(i)
}

推荐阅读