c# - 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();
}
}
解决方案
您不能使用 foreach 循环从列表中删除项目,因为它会更改当前正在操作的列表的结构。因此将抛出异常。
你可以使用 for 循环,但你需要反向使用它
for(int = list.count-1; i >= 0; i--)
{
if(list[i].id == 5)
list.RemoveAt(i)
}
推荐阅读
- c++ - C++ 用户定义函数返回不正确
- python - python中是否有任何相当于MVGC工具箱(来自MATLAB)的东西?
- pandas - 通过迭代源 pandas 数据帧动态附加值
- python - 用列表标记数据框列
- python - 在 MatPlotlib 中使散点图的线条平滑
- c# - 通过代码更改统一精灵图像并保存
- python - Python 3 在读取时无法解码某些字符
- javascript - 如何使用来自不同文件的 EmbedMessage?
- json - 如果条件与使用 JSON 模式草案 7 的相对参考
- python - 这是将 8 个 8 位整数数组转换为 1 个 64 位整数的安全方法吗