【问题标题】:Searching for an "id" saved in a list to get all the other fields搜索保存在列表中的“id”以获取所有其他字段
【发布时间】:2016-03-11 07:02:39
【问题描述】:

我有一个列表,其中每个索引都保存了患者的 ID、姓名、年龄、(...);我目前在搜索时使用此代码:

foreach (Paciente patient in pacientes)
{
    if (patient.id == Convert.ToInt32(txtIDP.Text))
    {
        txtNomeP.Text = patient.nome;
        txtIdadeP.Text = Convert.ToString(patient.idade);
        txtMoradaP.Text = patient.morada;
        txtContatoP.Text = patient.contato;
        txtEmailP.Text = patient.email;

        break;
    }
    else
    {
        txtNome.Clear();
        txtIdade.Clear();
        txtMorada.Clear();
        txtNumero.Clear();
        txtEmail.Clear();

        MessageBox.Show(
            "Não existe nenhum paciente com esse ID!", 
            "Error!", 
            MessageBoxButtons.OK, 
            MessageBoxIcon.Error);
    }
}

但我知道这是不正确的,因为它会在列表中搜索(如果存在),并且会在找到 id 之前自动显示找不到 id 的 MessageBox。当然,它会显示数组长度的 n 次错误。我怎样才能解决这个问题?谢谢。

【问题讨论】:

  • thisP = pacientes.Where( x=> x.ID == idFin).FirstOrDefault() 或将 MessageBox 移出循环

标签: c# arrays list search


【解决方案1】:

你可以这样做

var found = false;
foreach (Paciente patient in pacientes)
{
    if (patient.id == Convert.ToInt32(txtIDP.Text))
    {
        txtNomeP.Text = patient.nome;
        txtIdadeP.Text = Convert.ToString(patient.idade);
        txtMoradaP.Text = patient.morada;
        txtContatoP.Text = patient.contato;
        txtEmailP.Text = patient.email;
        found = true;
        break;
    }
}
if (!found)
{
    txtNome.Clear();
    txtIdade.Clear();
    txtMorada.Clear();
    txtNumero.Clear();
    txtEmail.Clear();
    MessageBox.Show("Não existe nenhum paciente com esse ID!", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

【讨论】:

  • 我现在想起了 bool 变量,无论如何谢谢你 Arghya! :)
【解决方案2】:

像这样使用 LINQ:

Paciente patient = pacientes.FirstOrDefault(x => x.id == Convert.ToInt32(txtIDP.Text));

if (patient == null)
{
    txtNome.Clear();
    txtIdade.Clear();
    txtMorada.Clear();
    txtNumero.Clear();
    txtEmail.Clear();
    MessageBox.Show("Não existe nenhum paciente com esse ID!", "Erro!", MessageBoxButtons.OK, MessageBoxIcon.Error);                
}
else
{
    txtNomeP.Text = patient.nome;
    txtIdadeP.Text = Convert.ToString(patient.idade);
    txtMoradaP.Text = patient.morada;
    txtContatoP.Text = patient.contato;
    txtEmailP.Text = patient.email;                
}

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多