In my form, I have four RadioButton s based on the user's choice, 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 repetitive, but also I cannot find a way to process all 4 RadioButtons in one line, which has only one variable related to the user's choice. myList is a List created class I, which has 4 string properties ( Name , Age , Gender , Occu )
source share