I've the following code for identifying which radio button should be marked as checked in a Windows Form, based on a stored value in a Dataset:
int rowNum = 0; //Row# is defined by system usage; value = 0 for example purposes
String storedValue = Convert.ToString(myDS.Tables["myTableName"].Rows[rowNum]["myColumn"]);
foreach (RadioButton button in this.myRBGroupBox.Controls) {
if (button.Text == storedValue) {
button.Checked = true;
}
}
Is this a good approach to solve this? is it a lambda alternative for this? Thanks for any help.
CodePudding user response:
OK, let's use a lambda to do the same thing without an explicit loop.
int rowNum = 0;
string storedValue = Convert.ToString(myDS.Tables["myTableName"].Rows[rowNum]["myColumn"]);
RadioButton rb = myRBGroupBox.Controls
.OfType<RadioButton>()
.FirstOrDefault(x => x.Text == storedValue));
if(rb != null) rb.Checked = true;
Is it better? Well, there are some improvements from your original code.
For example, the OfType<RadioButton>
guarantees to get only radio buttons from the GroupBox's controls and FirstOrDefault
stops the enumeration when the first radiobutton that match the condition is found.
But all these improvements can be done also in 'normal' code
foreach (Control ctrl in myRBGroupBox.Controls)
{
RadioButton rb = ctrl as RadioButton;
if (rb != null && rb.Text == storedValue) {
rb.Checked = true;
break;
}
}
Personally I find this last one more readable.