需要从checkedlistbox添加项目列表并删除一些

时间:2017-10-10 04:52:39

标签: c#

有一个包含字符串的清单。 每个循环都会检查已检查的项目,然后将这些项目添加到名为 mylist 的字符串列表中,前提是它们尚未添加。

我需要检查列表框中未选中的项目,并在取消选中项目框后从 mylist 中删除字符串。

Basicaly我有一个名为 mylist的列表我需要将任何已检查的项目从checkedboxlist添加到 mylist ,每当我取消选中一个项目时,都会从 mylist中删除相同的字符串

建议一些解决方案。提前致谢 。

3 个答案:

答案 0 :(得分:0)

下面的代码有一个foreach循环,遍历CheckBox列表,然后检查是否检查了每个项目,如果没有检查,则从myList获取该条目的索引,并使用RemoveAt属性从该条目中删除该条目列表使用索引。

foreach (var item in checkboxList) { if (!item.IsChecked) { int index = myList.IndexOf(item); if(index != -1) myList.RemoveAt(index); } }

答案 1 :(得分:0)

请非常友善,并审核您的下一个问题(How to Ask)...

利用活动anyCheckedListBox.ItemCheckMSDN):

public class Form1 : Form {

ListBox anyListBox;
CheckedListBox anyCheckedListBox;

public Form1() {
 anyListBox = new ListBox();
 Controls.Add(anyListBox);
 anyCheckedListBox = new CheckedListBox();
 anyCheckedListBox.Items.Add("test1");
 anyCheckedListBox.Items.Add("test2");
 anyCheckedListBox.Items.Add("test3");
 anyCheckedListBox.ItemCheck += AnyCheckedListBox_ItemCheck;
 Controls.Add(anyCheckedListBox);
}

private void AnyCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
    if (e.CurrentValue == CheckState.Unchecked)
        anyListBox.Items.Add(anyCheckedListBox.Items[e.Index]);
    else
        anyListBox.Items.Remove(anyCheckedListBox.Items[e.Index]);
}
}

请注意,使用这种快速而肮脏的解决方案,字符串必须是唯一的。

答案 2 :(得分:0)

天真的实现是在未检查项目的情况下在循环中添加对List.Remove的调用。假设您拥有的代码类似于@ AustinFrench的评论,例如:

foreach (var box in checkboxList)
{
    if (box.IsChecked && !myList.Contains(box.Text))
    {
        // if it's checked, add it to the list if it's not already there
        myList.Add(box.Text);
    }
    else if (!box.IsChecked)
    {
        // if it's not checked, try to remove it from the list
        myList.Remove(box.Text);
    }
}

请注意,需要在调用List.Remove之前检查项目是否存在。如果该项目不存在,它将简单地返回false。

另外请注意,这是一个O(n ^ 2)操作。它可能会检查复选框列表中每个项目的myList的全部内容。如果列表很长,您可以通过首先对列表进行排序并同时传递一对(或者至少排序myList以便您可以更有效地搜索它)来获得更好的性能。

或者,考虑完全替换myList的内容。这只需要通过您的复选框列表一次:

myList.Clear();
foreach (var box in checkboxList)
{
    if (box.IsChecked)
        myList.Add(box.Text);
}

或者,使用LINQ并利用List.AddRange

myList.Clear();
myList.AddRange(checkboxList.Where(box => box.IsChecked).Select(box => box.Text));