Foreach loop with condition

Is there a way to do the following in a single statement?

foreach(CheckBox subset in groupBox_subset.Controls) if(subset.Checked) { ... } 
+4
source share
4 answers

Sure:

 foreach (CheckBox subset in groupBox_subset.Controls .Cast<CheckBox>() .Where(c => c.Checked)) { ... } 

Cast is required because the Controls property implements only IEnumerable , not IEnumerable<T> , but LINQ mainly works on strongly typed collections. In other words, your existing code is actually closer to:

 foreach(Object tmp in groupBox_subset.Controls) { CheckBox subset = (CheckBox) tmp; if(subset.Checked) { ... } } 

If you want to ignore CheckBox , you should use OfType instead of Cast in the top fragment:

 foreach (CheckBox subset in groupBox_subset.Controls .OfType<CheckBox>() .Where(c => c.Checked)) { ... } 
+8
source

Yes there is:

 foreach(CheckBox subset in groupBox_subset.Controls.Cast<CheckBox>() .Where(x => x.Checked)) 

However, this only works if all items in Controls are of type CheckBox . If Controls has at least one element that is not a CheckBox , this will throw an exception. But also your code.

+7
source

You can use LINQ to select items matching this requirement:

 var controls = groupBox_subset.Controls.OfType<CheckBox>().Where(x => x.Checked); 
+7
source

You know that you are always one (or more) level of abstraction from the desired syntax that expresses your intentions:

 foreach(CheckBox checkedBox in groupBox_subset.CheckedBoxes()) { ... } 

Where the CheckedBoxes extension CheckedBoxes can be implemented by looking at other answers.

+3
source

All Articles