开发者

foreach loop with a condition

开发者 https://www.devze.com 2023-03-27 00:57 出处:网络
Is t开发者_JAVA技巧here a way to do the following in one statement? foreach(CheckBox subset in groupBox_subset.Controls)

Is t开发者_JAVA技巧here a way to do the following in one statement?

foreach(CheckBox subset in groupBox_subset.Controls)
    if(subset.Checked) { ... }


Sure:

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

The Cast call is required because the Controls property only implements IEnumerable, not IEnumerable<T>, but LINQ basically 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 be able to ignore non-CheckBox controls, you want the OfType method instead of Cast in the top snippet:

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


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 there is at least one item in Controls that is not a CheckBox, this will throw an exception. But so does your code.


You could use LINQ to select the elements matching this requirement:

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


You know, you're always one (or more) level of abstraction away from the desired syntax that expresses your intent:

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号