Reputation: 3430
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<CheckBox>() select chkbox).Any(b => b.Checked);
Upvotes: 0
Views: 1020
Reputation: 22379
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;
Upvotes: 0
Reputation: 196
Count can return the number of checked Checkboxes:
btnAgree.Enabled = (from chkbox in Controls.OfType<CheckBox>() select chkbox).Count(b => b.Checked) >= 2;
Upvotes: 0
Reputation: 3948
btnAgree.Enabled = (from chkbox in Controls.OfType<CheckBox>() select chkbox).Count(b => b.Checked) >= 2;
Should do the trick!
Upvotes: 2
Reputation: 1521
Try this:
btnAgree.Enabled = ((from chkbox in Controls.OfType<CheckBox>() select chkbox where chkbox.Checked = true).Count >= 2)
Upvotes: 1