如何遍历列表框中的项目然后删除这些项目?

19 c# listbox

我在尝试循环列表框然后删除项目时收到以下错误.

已修改此枚举器绑定的列表.只有在列表不更改时才能使用枚举器.

foreach (string s in listBox1.Items)
{
    MessageBox.Show(s);
    //do stuff with (s);
    listBox1.Items.Remove(s);
}
Run Code Online (Sandbox Code Playgroud)

如何删除项目并仍然循环浏览内容?

Mar*_*ell 37

要删除所有商品吗?如果是这样,foreach请先执行,然后使用Items.Clear()以后删除所有这些.

否则,可能由索引器向后循环:

listBox1.BeginUpdate();
try {
  for(int i = listBox1.Items.Count - 1; i >= 0 ; i--) {
    // do with listBox1.Items[i]

    listBox1.Items.RemoveAt(i);
  }
} finally {
  listBox1.EndUpdate();
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 25

其他人都发布了"向后退"的答案,所以我会提供替代方案:创建一个要删除的项目列表,然后在最后删除它们:

List<string> removals = new List<string>();
foreach (string s in listBox1.Items)
{
    MessageBox.Show(s);
    //do stuff with (s);
    removals.Add(s);
}

foreach (string s in removals)
{
    listBox1.Items.Remove(s);
}
Run Code Online (Sandbox Code Playgroud)

有时候"向后工作"的方法更好,有时上面的方法更好 - 特别是如果你正在处理一个有RemoveAll(collection)方法的类型.值得一提的是.

  • 如果是这种情况,那么问题中示例代码中的foreach循环就已经爆炸了.我正在做出与问题相同的假设,我认为这是非常合理的. (9认同)
  • -1.listBox1.Items可能包含除string之外的对象,在这种情况下将抛出InvalidCastException. (3认同)

nru*_*ann 11

这里我的解决方案没有后退,没有临时列表

while (listBox1.Items.Count > 0)
{
  string s = listBox1.Items[0] as string;
  // do something with s
  listBox1.Items.RemoveAt(0);
}
Run Code Online (Sandbox Code Playgroud)