【问题标题】:How can I check if username already exists in the file如何检查文件中是否已存在用户名
【发布时间】:2019-05-24 14:13:24
【问题描述】:

在课堂上,我正在输入数据以创建一个帐户。现在,用户输入的每个数据都保存在一个文件中。现在对于用户名,我想检查用户名是否已经存在于文件中。我怎样才能做到这一点?

      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);
    }  

【问题讨论】:

  • 1. DeserializeData 数据,2.检查List&lt;Client&gt; 是否包含输入的UsernameField

标签: c# file filter filtering


【解决方案1】:

您需要反序列化存储在文件中的现有数据。

var listOfClients = Client.DeserilizeData(fileName);

这将为您提供现有用户的列表。然后你可以使用 Linq 来检查 Username 是否已经存在

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 ));

【讨论】:

  • newUserName在哪里实现?
  • newUserName 是用户给定的值,var newUsername = Console.ReadLine();
  • 不知道为什么用户输入的值总是null:(
  • 根据你的代码更新了答案,你现在可以检查一下吗
  • 'var myRetrievedClients = Client.DeserializeData(filePath); bool 存在 = myRetrievedClients.Any(x => x.UsernameField.Equals(UsernameField));'
猜你喜欢
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-17
  • 2016-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多