string number = txtNumber.Text;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
break;
}
else
{
MessageBox.Show("Account Number not found");
}
}
大家好,我在这里和C#相当新。所以我有一个带有客户信息的类账户存储在一个文本文件中。我想遍历数组tabAccounts [200]并查看输入的用户编号是否与文本文件中的用户编号相对应。它工作正常,但当我输入时说222它开始从乞讨循环直到它找到数字,如果它没有它只是保持循环和消息“帐号未找到”不断出来。当我删除else语句它工作正常但我希望它当用户输入错误的数字时,一个消息框将显示...希望你们得到它:(尝试谷歌搜索但没有找到任何东西..
答案 0 :(得分:7)
使用LINQ可以做得更有效:
var account = tabAccounts.SingleOrDefault(a => a.Number == txtNumber.Text);
if(account != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + account.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
对于您的原始代码:问题是,每次循环没有找到任何内容时,您在循环中显示消息。这是一个接近原始语法的重写,只是为了告诉你如何做到这一点:
Account foundAccount = null;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
foundAccount = ac;
break;
}
}
if(foundAccount != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + foundAccount.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
答案 1 :(得分:3)
实现目标所需的最低费用:
string number = txtNumber.Text;
bool found = false;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
found = true;
break;
}
}
if (!found)
MessageBox.Show("Account Number not found");
答案 2 :(得分:3)
问题在于,您不必等到搜索结果显示"Account Number not found"
后,每次找到不匹配的Account
时都会显示。我会使用FirstOrDefault
扩展方法重写它。
string number = txtNumber.Text;
Account ac = tabAccounts.FirstOrDefault(x => x.Number == txtNumber.Text);
if (ac != null)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + ac.Client;
}
else
{
MessageBox.Show("Account Number not found");
}
答案 3 :(得分:1)
执行此操作的最佳方法是在找到元素时设置标志,然后在循环外部显示
bool found = false;
string client;
string number = txtNumber.Text;
foreach (Account ac in tabAccounts)
{
if (txtNumber.Text == ac.Number)
{
found = true;
client = ac.Client;
break;
}
}
if (found)
{
this.Height = 328;
lblWelcome.Text = "Welcome: " + client;
}
else
{
MessageBox.Show("Account Number not found");
}