I've got 2 groups of controls.
The first one contains 3 textboxes named a, b and c. They can all be enabled or disabled at the same time.
The second group contains 2 textboxes (d and e). One and only one is enabled at a time.
Now, I have a boolean variable (named ok), which is true if:
And I want to check it all in one call.
Here's what I get:
bool ok =
(
(
(
(!a.IsEnabled ||
(a.IsEnabled && !String.IsNullOrWhiteSpace(a.Text))) &&
(!b.IsEnabled ||
(b.IsEnabled && !String.IsNullOrWhiteSpace(b.Text))) &&
(!c.IsEnabled ||
(c.IsEnabled && !String.IsNullOrWhiteSpace(c.Text))) &&
(a.IsEnabled || b.IsEnabled || c.IsEnabled)
)
) &&
(
(!d.IsEnabled ||
(d.IsEnabled && !String.IsNullOrWhiteSpace(d.Text))) &&
(!f.IsEnabled ||
(f.IsEnabled && !String.IsNullOrWhiteSpace(f.Text)))
)
);
It's quite heavy on the eye, any idea on how to simplify it?
Why not stick all your controls into a list an query them using LINQ
var group1 = new[] { a, b, c };
var group2 = new[] { d, e };
var all = group1.Concat(group2);
// assuming all controls are the same or implement the same interface
Func<ControlType, bool> enabledAndNotEmpty = (x) => {
return x.IsEnabled && !String.IsNullOrWhiteSpace(x.Text);
};
Func<ControlType, bool> enabledAndEmpty = (x) => {
return x.IsEnabled && String.IsNullOrWhiteSpace(x.Text);
};
var ok = group1.Any(enabledAndNotEmpty) && // a, b or c is enabled & not empty
group2.Any(enabledAndNotEmpty) && // d or e is enabled & not empty
!all.Any(enabledAndEmpty); // none of the above are enabled & empty