String.Split结果的问题

ale*_*eks 0 c#

我试图从文本文件中加载4行:

email:pass
email1:pass1
email2:pass2
email3:pass3
Run Code Online (Sandbox Code Playgroud)

我使用了string.split,但是当我尝试添加到我的列表时,它加载不好.

这是我尝试过的:

List<string> AccountList = new List<string>();
Console.Write("File Location: ");
string FileLocation = Console.ReadLine();
string[] temp = File.ReadAllLines(FileLocation);
string[] tempNew = new string[1000];

int count = 0;
foreach(var s in temp)
{
    AccountList.Add(s.Split(':').ToString());
    count++;
}
Run Code Online (Sandbox Code Playgroud)

我检查了字符串在列表中的外观,它们是这样的:

System.String[]
Run Code Online (Sandbox Code Playgroud)

我希望它是这样的:

AccountList[0] = email
AccountList[1] = pass
AccountList[2] = email1
AccountList[3] = pass1
Run Code Online (Sandbox Code Playgroud)

Oli*_*bes 5

String.Split 产生一个字符串数组

foreach(var s in temp)
{
    string[] parts = s.Split(':');
    string email = parts[0];
    string pass = parts[1];
    ...
}
Run Code Online (Sandbox Code Playgroud)

要存储这两条信息,请创建一个帐户:

public class Account
{
    public string EMail { get; set; }
    public string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后将您的帐户列表声明为List<Account>:

var accountList = new List<Account>();
foreach(var s in File.ReadLines(FileLocation))
{
    string[] parts = s.Split(':');
    var account = new Account { EMail = parts[0], Password = parts[1] };
    accountList.Add(account);
}
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要temp变量.File.ReadLines随着循环的进行读取文件,因此整个文件不需要存储在内存中.请参阅:File.ReadLines方法(Microsoft Docs).

无需数数.你可以得到计数

int count = accountList.Count;
Run Code Online (Sandbox Code Playgroud)

与使用电子邮件和密码交错的列表相比,此列表更易于处理.

您可以按索引访问帐户

string email = accountList[i].EMail;
string pass = accountList[i].Password;
Run Code Online (Sandbox Code Playgroud)

要么

Account account = accountList[i];
Console.WriteLine($"Account = {account.EMail}, Pwd = {account.Password}");
Run Code Online (Sandbox Code Playgroud)