在我的表单中,我有四个
单选按钮
,基于用户的选择,执行以下代码: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
是我创建的一个类的 List
,该类具有4个 string
属性(Name
、Age
、Gender
、Occu
)。
(radioButtonName.Checked && item.Name == textBoxSearch.Text) || (radioButtonAge.Checked && item.Age == textBoxSearch.Text)...
- Nkosi(...)
。 - Dmitry Bychenko&&
会先被计算。 - Orkhan AlikhanovSelect
中返回了string
:.Select(item => string.Format(...));
问题中的代码使用了匿名类,我们无法在那里声明/覆盖方法。 - Dmitry Bychenko