简体   繁体   English

如何对来自checkedlistbox C#的所有未检查项目进行循环?

[英]How to do a loop on all unchecked items from checkedlistbox C#?

I was working on a method and then I realized that I had a foreach loop that ran through all checkedItems, instead of running through all unchecked item. 我正在研究一个方法然后我意识到我有一个遍历所有checkedItems的foreach循环,而不是遍历所有未检查的项目。

foreach ( object itemChecked in checkedListBox1.CheckedItems)
{(...)}

I was wondering if there is way to do this without changing the code too much. 我想知道是否有办法在不改变代码的情况下做到这一点。 Regards 问候

Two options: 两种选择:

  1. Loop through all Items and check them against the CheckedItems . 遍历所有Items并针对CheckedItems检查它们。
  2. Use LINQ. 使用LINQ。

Option 1 选项1

foreach (object item in checkedListBox1.Items)
{
  if (!checkedListBox1.CheckedItems.Contains(item))
  {
    // your code
  }
}

Option 2 选项2

IEnumerable<object> notChecked = (from object item in checkedListBox1.Items
                                  where !checkedListBox1.CheckedItems.Contains(item)
                                  select item);

foreach (object item in notChecked)
{
  // your code
}

Cast the items as a CheckBox enumerable then you can loop: 将项目作为可枚举的CheckBox投射,然后您可以循环:

foreach (CheckBox cb in checkedListBox1.Items.Cast<CheckBox>())
{
    if (!cb.Checked)
    {
        // your logic
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM