[英]How can I check if username already exists in the file
在課堂上,我正在輸入數據來創建一個帳戶。 現在,用戶輸入的每個數據都保存在一個文件中。 現在,對於用戶名,我想檢查用戶名是否已存在。 我怎樣才能做到這一點?
public void CreateAccount()
{
Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-");
Console.WriteLine("Enter a Username: ");
Client usernameField = new Client("Username")
{
UsernameField = Console.ReadLine()
};
string filePath = "C:\\createaccount.txt"
Client.SerializeData(accountData, filePath);
public static void SerializeData(List<Client> userToSerialize, string
filePath)
{
FileReadWrite<Client>.SerializeData(userToSerialize, filePath);
}
public static List<Client> DeserializeData<Client>(string filePath)
{
return FileReadWrite<Client>.DeserializeData<Client>(filePath);
}
您需要反序列化存儲在文件中的現有數據。
var listOfClients = Client.DeserilizeData(fileName);
這將為您提供現有用戶的列表。 然后您可以使用Linq檢查用戶名是否已經存在
var exists = listOfclients.Any(x=>x.UsernameField.Equals(newUserName));
如果用戶名不區分大小寫,則需要使用
var exists = listOfclients.Any(x=>x.UsernameField.Equals(newUserName,StringComparison.OrdinalIgnoreCase));
根據您的代碼進行更新。
Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-");
Console.WriteLine("Enter a Username: ");
Client usernameField = new Client("Username")
{
UsernameField = Console.ReadLine()
};
var listOfClients = Client.DeserilizeData(fileName);
var exists = listOfclients.Any(x=>x.UsernameField.Equals(usernameField.UsernameField ));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.