gpt4 book ai didi

c# - 如果项目存在于另一个 ListBox 中,则从 ListBox 中删除项目

转载 作者:行者123 更新时间:2023-11-30 20:00:15 28 4
gpt4 key购买 nike

如果这些值存在于另一个 ListBox 中,我将尝试从 ListBox 中删除数字项。我的代码似乎不起作用,而且我无法在线找到任何帮助。 ListBox1 由 Array 填充,ListBox2 由 DataSet 表填充 (fyi)。

另外供引用:我没有向列表框添加和项目或选择...只是想比较两者并从 ListBox1 中删除 ListBox2 项目(如果它们通过按下按钮自动存在)。谢谢,

private void button1_Click(object sender, EventArgs e)
{
foreach (int item in listBox1.Items)
{
if (listBox2.Items.Contains(item))
{
listBox1.Items.Remove(item);
}
}
}

最佳答案

好吧,您只是在代码中引用了一个列表框 - 我想您会想要:

private void button1_Click(object sender, EventArgs e) {

foreach (int item in listBox1.Items)
{
if (listBox2.Items.Contains(item)) // notice change of reference
{
listBox1.Items.Remove(item);
}
}

但是,这会导致错误,因为您在迭代 ListBox 的项目时修改了它。一种安全删除项目的方法是在集合上向后迭代:

for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
int item = listBox1.Items[i];
if (listBox2.Items.Contains(item)) // notice change of reference
{
listBox1.Items.RemoveAt(i);
}
}

关于c# - 如果项目存在于另一个 ListBox 中,则从 ListBox 中删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21685243/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com