如何对来自 checkedlistbox C# 的所有未选中项目进行循环?
How to do a loop on all unchecked items from checkedlistbox C#?
我正在研究一种方法,然后我意识到我有一个 foreach 循环,该循环 运行 遍历所有选中的项目,而不是 运行 遍历所有未选中的项目。
foreach ( object itemChecked in checkedListBox1.CheckedItems)
{(...)}
我想知道是否有办法在不过多更改代码的情况下做到这一点。
此致
两个选项:
- 遍历所有
Items
并对照 CheckedItems
. 检查它们
- 使用 LINQ。
选项 1
foreach (object item in checkedListBox1.Items)
{
if (!checkedListBox1.CheckedItems.Contains(item))
{
// your code
}
}
选项 2
IEnumerable<object> notChecked = (from object item in checkedListBox1.Items
where !checkedListBox1.CheckedItems.Contains(item)
select item);
foreach (object item in notChecked)
{
// your code
}
将项目转换为可枚举的 CheckBox,然后您可以循环:
foreach (CheckBox cb in checkedListBox1.Items.Cast<CheckBox>())
{
if (!cb.Checked)
{
// your logic
}
}
我正在研究一种方法,然后我意识到我有一个 foreach 循环,该循环 运行 遍历所有选中的项目,而不是 运行 遍历所有未选中的项目。
foreach ( object itemChecked in checkedListBox1.CheckedItems)
{(...)}
我想知道是否有办法在不过多更改代码的情况下做到这一点。 此致
两个选项:
- 遍历所有
Items
并对照CheckedItems
. 检查它们
- 使用 LINQ。
选项 1
foreach (object item in checkedListBox1.Items)
{
if (!checkedListBox1.CheckedItems.Contains(item))
{
// your code
}
}
选项 2
IEnumerable<object> notChecked = (from object item in checkedListBox1.Items
where !checkedListBox1.CheckedItems.Contains(item)
select item);
foreach (object item in notChecked)
{
// your code
}
将项目转换为可枚举的 CheckBox,然后您可以循环:
foreach (CheckBox cb in checkedListBox1.Items.Cast<CheckBox>())
{
if (!cb.Checked)
{
// your logic
}
}