请教这个循环怎么写

ertfvedc34 2011-07-03 08:26:35
把listbox1当中,不等于"aaa"的项删除

我的写法是这样的:
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < listBox1.Items.Count; i++)
{

if (listBox1.Items[i].ToString() != "aa")
{

listBox1.Items.Remove(listBox1.Items[i]);
}
}
}

但这样做,就出现了问题,一下子删不完,因为,边删,Count的数字就会变化,要多点几次button,才能删完,能不能用foreach,请大师指教
...全文
45 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
szfocus 2011-07-03
  • 打赏
  • 举报
回复
int i = this.listBox1.Items.Count-1;
for (int ii = i; ii >= 0; ii--)
{
if (this.listBox1.Items[ii].ToString() != "aaa")
{
this.listBox1.Items.RemoveAt(ii);
}
}
x8bits 2011-07-03
  • 打赏
  • 举报
回复
先查找,再删除

List<object> aaaItems = new List<object>();
foreach (object s in listBox1.Items)
{
if (s.ToString() == "aaa")
{

aaaItems.Add(s);
}
}

foreach (object o in aaaItems)
{
listBox1.Items.Remove(o);
}

110,571

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧