在我的表單中我有四個RadioButton
S,根據用戶的選擇,該代碼被執行:處理重複邏輯冗餘代碼的最佳方法是什麼?
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);
}
}
}
的代碼似乎很冗餘和重複,但我也不能找到一種方法來處理所有4個單選按鈕在只有一個變量鏈接到用戶選擇的單行中。 myList
是I類創建具有4種string
性質(Name
,Age
,Gender
,Occu
)的List
快速的問題應該在單選按鈕檢查和文本比較用括號括起來或者它沒有關係?例如'(radioButtonName.Checked && item.Name == textBoxSearch.Text)|| (radioButtonAge.Checked && item.Age == textBoxSearch.Text)...' – Nkosi
@Nkosi:在上下文中沒有關係;但是,如果帶有父項的版本更易於讀取*,則可以添加'(...)' –
@Nkosi請參閱[此答案](http://stackoverflow.com/a/1196738/5555803)。首先得到評估 –