开发者

Reducing variable usage while checking a group of controls

开发者 https://www.devze.com 2023-03-14 12:55 出处:网络
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:

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.

0

精彩评论

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