简体   繁体   中英

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.

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 .
  2. Use LINQ.

Option 1

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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