[英]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.现在我正在使用 2 个单独但连接的字符串,我将它们与用户输入进行比较,以确定他们是否输入了正确的登录凭据。
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:我对
Code
vs Word
有点困惑,但这是其中的要点:
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:然后您可以使用 LINQ 来查看是否有任何组合与用户输入匹配:
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.请注意,比较期望大小写也匹配,正如它所写的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.