我问用户他/她的选民ID是什么,如果它在我的列表中,该程序将显示一个消息框,显示他/她的名字。然后如果用户按下“确定”,它将重定向到另一种形式。
这是我的代码:
public class Voter{
public string voterName {get; set;}
public int voterID {get; set;}
public override string ToString()
{
return " Name: " + voterName;
}
}
void BtnValidateClick(object sender, EventArgs e)
{
int id = Int32.Parse(tbVotersID.Text);
List<Voter> voters = new List<Voter>();
voters.Add(new Voter() {voterName = "voter #1", voterID = 12345});
voters.Add(new Voter() {voterName = "voter #2", voterID = 67890});
voters.Add(new Voter() {voterName = "voter #3", voterID = 11800});
if (voters.Contains(new Voter {voterID = id})){
//prompts a messagebox that shows voterName
}
else{
MessageBox.Show("ID not recognized.", "ID ENTRY", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
答案 0 :(得分:1)
您可以将LINQ与Find()结合使用来获取第一个结果的选民名称。检查其null是否为null,否则显示MessageBox()。 https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.find?view=netframework-4.8
void BtnValidateClick(object sender, EventArgs e)
{
int id = Int32.Parse(tbVotersID.Text);
List<Voter> voters = new List<Voter>();
voters.Add(new Voter() {voterName = "voter #1", voterID = 12345});
voters.Add(new Voter() {voterName = "voter #2", voterID = 67890});
voters.Add(new Voter() {voterName = "voter #3", voterID = 11800});
var voterName = voters.Find(voter => voter.voterID == id)?.voterName;
if (!string.IsNullOrEmpty(voterName)){
MessageBox.Show(voterName);
}
else{
MessageBox.Show("ID not recognized.", "ID ENTRY", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}