简体   繁体   中英

How can I use a dictionary to replace 2 strings that are being compared?

string[] UserCodes = { "admin", "testcode" };
string[] UserWords = { "123", "testword" };

public void Button_Clicked(object sender, EventArgs e)
{
    for (int i = 0; i < UserCodes.Length; i++)
    {
        if (UserCode.Text.Equals(UserCodes[i])  && UserWord.Text.Equals(UserWords[i]))
        {
            Navigation.PushAsync(new HomePage());
            return;
        }
        else
        {
            DisplayAlert("Something Went Wrong", "Incorrect Password or Username", "Try Again");
        }
    }         
}

Right now I am using 2 separate, but conjunct strings, which I am comparing to user input to determine whether or not they entered the correct login credentials.

public void d(string[] args)
  
    {
        IDictionary<string, string> LogCred = new Dictionary<string, string>();
        LogCred.Add("admin", "123");
        LogCred.Add("testcode", "test");

    }

This is the dictionary I tried to make.

My question is how can I use a dictionary to acomplish the same results?

Assuming this is a test app, and putting aside security for now, you can initialize a Dictionary with the username/password combinations. I'm a bit confused on Code vs Word , but this is jist of it:

 Dictionary<string, string> users = new Dictionary<string, string>
 {
   //['code']  = 'word'  
     ["admin"] = "123",
     ["testcode"] = "testword"
 };

Then you can use LINQ to see if any of the combos match the user input:

public static void Button_Clicked(object sender, EventArgs e)
{
    var user = users.FirstOrDefault(x => x.Key == UserCode.Text && x.Value == UserWord.Text);

    if(user != null)
    {
         //got a match
    }
    else 
    {
        //no matches
    }
}

Note the comparison is expecting the casing to match as well, as it's written.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM