Reducing variable usage while checking a group of controls
I only want a warning to go up if none of the check boxes inside a group box are checked. This is what I'm using right now:
foreach(CheckBox i in groupBox_productType.Controls) {
开发者_StackOverflow if(i.Checked){
isChecked = true;
break;
}
}
if(!isChecked) { /* warning goes here */ }
Without creating a one-time use variable (isChecked
), is there a way of doing what I want ?
You could do:
if(!group_Box.productType.Controls.OfType<CheckBox>().Any( c => c.Checked ) )
{
...
}
This will also short circuit on the first "true" value, the same as your break.
Edit: Included cast to type of Checkbox per comment.
Something like:
if (!groupBox_productType.Controls.OfType<CheckBox>().Any(checkBox => checkBox.Checked))
{
//Warning goes here.
}
Any will break soon as it find a match to any of the Controls in the group by of the type CheckBox that are checked.
精彩评论