【问题标题】:Need to add items to list from checkedlistbox and remove some需要从checkedlistbox添加项目并删除一些
【发布时间】:2017-10-10 04:52:38
【问题描述】:

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

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

基本上,我有一个名为 mylist 的列表,我需要将任何选中的项目从 checkboxlist 添加到 mylist 并且每当我取消选中一个项目时,从 mylist 中删除相同的字符串 。

提出一些解决方案。提前致谢 。

【问题讨论】:

  • 代码在哪里?
  • 请用代码 sn-p 更新问题
  • 没有代码,但我猜foreach (var box in checkboxList) { if (box.IsChecked) { myList.Add(box.Text;}}

标签: c#


【解决方案1】:

请善待并检查您的下一个问题 (How to Ask)...

利用活动anyCheckedListBox.ItemCheck (MSDN):

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】:

    如果未选中该项目,最简单的实现是在循环中添加对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));
    

    【讨论】:

      【解决方案3】:

      下面的代码有一个foreach 循环,它遍历CheckBoxes 的列表,然后检查每个项目是否被选中。如果未选中,则从 myList 获取该条目的索引,并使用 RemoveAt 方法使用索引从列表中删除该条目。

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

      【讨论】:

        猜你喜欢
        • 2023-03-20
        • 1970-01-01
        • 2019-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-15
        相关资源
        最近更新 更多