如何使用数组验证用户名和密码

时间:2013-05-08 05:03:12

标签: c# arrays

您好我想创建一个登录界面,用户将输入用户名和密码。但如何使用数组验证?请帮忙谢谢

        int[] username = { 807301, 992032, 123144 ,123432};

        string[] password = {"Miami", "LosAngeles" ,"NewYork" ,"Dallas"};

        if (username[0].ToString() == password[0])
        {
            MessageBox.Show("equal");
        }
        else
        {
            MessageBox.Show("not equal");
        }

2 个答案:

答案 0 :(得分:0)

您需要先从数组username中找到用户名的索引。然后根据该索引比较密码数组的密码。

int[] username = { 807301, 992032, 123144, 123432 };

string[] password = { "Miami", "LosAngeles", "NewYork", "Dallas" };

int enteredUserName = 123144;
string enteredPassword = "NewYork";

//find the index from the username array
var indexResult = username.Select((r, i) => new { Value = r, Index = i })
                          .FirstOrDefault(r => r.Value == enteredUserName);
if (indexResult == null)
{
    Console.WriteLine("Invalid user name");
    return;
}

int indexOfUserName = indexResult.Index;

//Compare the password from that index. 
if (indexOfUserName < password.Length && password[indexOfUserName] == enteredPassword)
{
    Console.WriteLine("User authenticated");
}
else
{
    Console.WriteLine("Invalid password");
}

答案 1 :(得分:0)

为什么不使用字典?字典是某种数组,但它结合了匹配的键和值。 TryGetValue会尝试查找用户名。如果未找到用户名,则该函数将返回false,否则将返回true和匹配的密码。此密码可用于验证用户输入的密码。

Dictionary<int, string> userCredentials = new Dictionary<int, string>
{
    {807301, "Miami"},
    {992032, "LosAngeles"},
    {123144, "NewYork"},
    {123432 , "Dallas"},
};

int userName = ...;
string password = ...;

string foundPassword;
if (userCredentials.TryGetValue(userName, out foundPassword) && (foundPassword == password))
{
    Console.WriteLine("User authenticated");
}
else
{
    Console.WriteLine("Invalid password");
}