Checkbox validation with LINQ
As part of learning LINQ, i got stuck up with the following problem.
A windows form with N number of Checkboxes and a button. The button should be enabled only when, the user checks\selected any two checkboxes. I am trying to implement this using LINQ, but couldn't achieve the desired results.
I used the following code, but works only when any one of the Checkbox is selected.
btnAgree.Enabled = (from chkbox in Controls.OfType<开发者_如何学PythonCheckBox>() select chkbox).Any(b => b.Checked);
btnAgree.Enabled = (from chkbox in Controls.OfType<CheckBox>() select chkbox).Count(b => b.Checked) >= 2;
Should do the trick!
Try this:
btnAgree.Enabled = ((from chkbox in Controls.OfType<CheckBox>() select chkbox where chkbox.Checked = true).Count >= 2)
Count can return the number of checked Checkboxes:
btnAgree.Enabled = (from chkbox in Controls.OfType<CheckBox>() select chkbox).Count(b => b.Checked) >= 2;
Do you want the Linq expression to return true if and only if exactly 2 checkboxes are selected?
If so, this should do the trick:
btnAgree.Enabled = Controls.OfType<CheckBox>()
.Count(b => b.Checked) == 2;
精彩评论