Mohamed Ahmed Mohamed Ahmed - 3 months ago 7
C# Question

Best way to handle redundant code that has repeated logic?

In my form I have four

RadioButton
s, based on user selection, this code is executed:

private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
if (radioButtonName.Checked)
{
var Qr = from n in mylist where n.Name == textBoxSearch.Text select new { n.Name, n.Age, n.Occu, n.Gender };
foreach (var item in Qr)
{
listBox1.Items.Add("Name: " + item.Name + " " + " Age: " + item.Age + " " + " Occupation: " + item.Occu + " " + " Gender: " + item.Gender);
}
}
if (radioButtonAge.Checked)
{
var Qr = from n in mylist where n.Age == textBoxSearch.Text select new { n.Name, n.Age, n.Occu, n.Gender };
foreach (var item in Qr)
{
listBox1.Items.Add("Name: " + item.Name + " " + " Age: " + item.Age + " " + " Occupation: " + item.Occu + " " + " Gender: " + item.Gender);
}

}
if (radioButtonGender.Checked)
{
var Qr = from n in mylist where n.Gender == textBoxSearch.Text select new { n.Name, n.Age, n.Occu, n.Gender };
foreach (var item in Qr)
{
listBox1.Items.Add("Name: " + item.Name + " " + " Age: " + item.Age + " " + " Occupation: " + item.Occu + " " + " Gender: " + item.Gender);
}
}
if (radioButtonOccupation.Checked)
{
var Qr = from n in mylist where n.Occu == textBoxSearch.Text select new { n.Name, n.Age, n.Occu, n.Gender };
foreach (var item in Qr)
{
listBox1.Items.Add("Name: " + item.Name + " " + " Age: " + item.Age + " " + " Occupation: " + item.Occu + " " + " Gender: " + item.Gender);
}

}

}


The code seems very redundant and repeated, but also I can't find a way to handle all 4 RadioButtons in a single line that has only one variable linked to user choice.
myList is a
List
of a class I created that has 4
string
properties (Name, Age, Gender, Occu)

Answer

The only difference is in filter (where) all the other can be combined:

 private void button1_Click(object sender, EventArgs e) {
   var lines = mylist
     .Where(item => radioButtonName.Checked && item.Name == textBoxSearch.Text ||
                    radioButtonAge.Checked && item.Age == textBoxSearch.Text ||
                    radioButtonGender.Checked && item.Gender == textBoxSearch.Text ||
                    radioButtonOccupation.Checked && item.Occu == textBoxSearch.Text)
     .Select(item => string.Format("Name: {0} Age: {1} Occupation: {2} Gender: {3}",
                                    item.Name, item.Age, item.Occu, item.Gender));  

   listBox1.Items.Clear();

   foreach (string line in lines)
     listBox1.Items.Add(line);   
 }