使用foreach作为对序列遍历list(或array)
本文关键字:list array 遍历 foreach 使用 | 更新日期: 2023-09-27 18:10:53
我正在创建一个简单的程序,从Customers.txt文件中读取用户名和密码,并验证它是否正确。txt的格式为用户名和密码的序列用逗号分隔(忽略安全问题):
JaneDoeJohnDoe, 1234年,5678年…
是否可以创建一个foreach
循环来迭代strArray[]
并检查对{strArray[0]
, strArray[1]
}然后{strArray[2]
, strArray[3]
}等等,以查看用户是否输入了正确的凭据?
private void enter_click_Click(object sender, RoutedEventArgs e)
{
StreamReader reader1 = new StreamReader("Customers.txt");
string text = reader1.ReadToEnd();
reader1.Close();
string[] Strarray = text.Split(',');
StreamReader reader2 = new StreamReader("Admin.txt");
string text2 = reader2.ReadToEnd();
reader2.Close();
string[] AdminArray = text2.Split(',');
if (username_txt.Text == AdminArray[0] && passwordBox1.Password == AdminArray[1])
{
AdminPage admin = new AdminPage();
admin.Activate();
admin.Show();
method.CheckDate();
return;
}
if (username_txt.Text == Strarray[0] && passwordBox1.Password == Strarray[1])
{
ATM_Screen atm = new ATM_Screen();
atm.Activate();
atm.Show();
method.CheckDate();
return;
}
是的,你可以这样做:
var usernames = Strarray.Where((s, i) => { return i % 2 == 0; });
var passwords = Strarray.Where((s, i) => { return i % 2 != 0; });
var userPasswords = usernames.Zip(passwords, (l, r) => new { username = l, password = r });
foreach(var userPassword in userPasswords) {
if (userPassword.username == "rob" && userPassword.password == "robspassword") {
}
}
根据注释编辑:
您可以为多个有效凭据执行此操作:
var allowedCredentials = new List<Tuple<String, String>> {
new Tuple<String, String>("Rob", "Robspassword"),
new Tuple<String, String> ("SomeoneElse", "SomeoneElsespassword"
};
var inputCredentials = new List<string> { "Rob","Robspassword","Rob","Notrobspassword" };
var usernames = inputCredentials.Where((s, i) => { return i % 2 == 0; });
var passwords = inputCredentials.Where((s, i) => { return i % 2 != 0; });
var userPasswords = usernames.Zip(passwords, (l, r) => new { username = l, password = r });
foreach(var userPassword in userPasswords) {
if (allowedCredentials.Any(ac => ac.Item1 == userPassword.username
&& ac.Item2 == userPassword.password)
{
//Valid
}
}
使用foreach
很难从序列中获得元素对:
- 你可以正常地遍历序列,在奇数迭代中记住第一个元素,在每个偶数迭代中执行操作
- 您可以先使用LINQ和索引将序列转换成成对,或者压缩偶数和奇数一半。
收集对方法:
string name;
bool even = false;
foreach(var text in items)
{
if (even)
{
var password = item;
// check name, password here
}
else
{
name = text;
}
even = !even;
}
Zip-based方法
foreach(var pair in items
.Where((v,id)=>id % 2 == 1) // odd - names
.Zip(items.Where((v,id)=>id % 2 == 0), // even - passwords
(name,password)=> new { Name = name, Password = password}))
{
// check pair.Name, pair.Password
}
注意:使用常规的for
循环,增量为2会更容易。