如何通过获取ID显示名称?

问题描述 投票:0回答:1

我问用户他/她的选民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);
        }

    }
c# winforms messagebox
1个回答
0
投票

您可以将LINQ与Find()一起使用,以获取第一个结果的voterName。检查其null是否为null,否则显示MessageBox()。 https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.exists?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 => voterID == id)?.voterName;
    if (!string.IsNullOrEmpty(voterName)){
            MessageBox.Show(voterName);
        }
    else{
    MessageBox.Show("ID not recognized.", "ID ENTRY", MessageBoxButtons.OK, 
    MessageBoxIcon.Error);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.