如何通过用户输入(控制台应用程序)在 C# 中使用带有列表的 IndexOf 方法自动增加 int userid?

How to auto increment int userid with IndexOf method with a List in C# via user input (Console Application)?

我使用以下方法(注册)的目标是在管理员填写用户详细信息时自动增加用户 ID,并将其全部保存在一个列表中,最终将新添加的用户写入 csv 文件。每次加载应用程序时都会读取 csv 文件。最后两种方法非常有效。

这是进行用户输入以及我想自动递增用户标识的方法:

public void Register(List<User> users)
        {
            
            int userid = users.LastIndexOf(userid);
            if (userid < users.LastIndexOf(userid))
            {
                userid++;
            }

            // Get user input
            Console.WriteLine("Enter username:");
            string username = Console.ReadLine();

            Console.WriteLine("Enter email:");
            string email = Console.ReadLine();

            Console.WriteLine("Enter password:");
            string password = Console.ReadLine();

            Console.WriteLine("Enter userrole (typ admin, purchase or sales):");
            string userrole = Console.ReadLine();

            // Create fresh instance to save input in memory
            User user = new User(userid, username, email, password, userrole);
            
            // Adds the user to the excisting list
            users.Add(user);

            FileOperations fo = new FileOperations();
            // Calling the method from FileOperations.cs to write the List here to a CSV file
            fo.WriteUsersToCSV(users);
            
        }

我收到以下错误:

RegisterManager.cs(16,44): error CS1503: Argument 1: cannot convert from 'int' to 'GimpiesConsoleOOcsvListUI.User' [/home/pascalmariany/Projects/Csharp/GimpiesConsoleOOcsvList/GimpiesConsoleOOcsvListUI/GimpiesConsoleOOcsvListUI.csproj]
RegisterManager.cs(17,44): error CS1503: Argument 1: cannot convert from 'int' to 'GimpiesConsoleOOcsvListUI.User' [/home/pascalmariany/Projects/Csharp/GimpiesConsoleOOcsvList/GimpiesConsoleOOcsvListUI/GimpiesConsoleOOcsvListUI.csproj]
RegisterManager.cs(16,44): error CS0165: Use of unassigned local variable 'userid' [/home/pascalmariany/Projects/Csharp/GimpiesConsoleOOcsvList/GimpiesConsoleOOcsvListUI/GimpiesConsoleOOcsvListUI.csproj]

当我尝试使用下面的代码时,它会保存并写入 csv 文件,但不会继续自动增加用户 ID:

public void Register(List<User> users)
        {
           
            int userid = 3;
            userid++;

            // Get user input
            Console.WriteLine("Enter username:");
            string username = Console.ReadLine();

            Console.WriteLine("Enter email:");
            string email = Console.ReadLine();

            Console.WriteLine("Enter password:");
            string password = Console.ReadLine();

            Console.WriteLine("Enter userrole (typ admin, purchase or sales):");
            string userrole = Console.ReadLine();

            // Create fresh instance to save input in memory
            User user = new User(userid, username, email, password, userrole);
            
            // Adds the user to the excisting list
            users.Add(user);

            FileOperations fo = new FileOperations();
            // Calling the method from FileOperations.cs to write the List here to a CSV file
            fo.WriteUsersToCSV(users);
            
        }

CSV 输出:

userid,username,email,password,userrole
1,Inkoop,inkoop@gimpies.nl,123,purchase
2,Verkoop,verkoop@gimpies.nl,123,sales
3,Beheer,beheer@gimpies.nl,123,admin
4,Bas,bas@bas.nl,123,admin
4,Tim,tim@tim.nl,123,sales

哦,前 3 个用户是默认用户!他们需要留在 CSV 中。这就是为什么我开始 int userid = 3.

更新反馈:

我根据反馈调整了方法:

public void Register(List<User> users)
        {
            
            User usr = users.OrderByDescending(u => u.userid).FirstOrDefault();
            int userid = (usr == null ? 1 : usr.userid++);

            // Get user input
            Console.WriteLine("Enter username:");
            string username = Console.ReadLine();

            Console.WriteLine("Enter email:");
            string email = Console.ReadLine();

            Console.WriteLine("Enter password:");
            string password = Console.ReadLine();

            Console.WriteLine("Enter userrole (typ admin, purchase or sales):");
            string userrole = Console.ReadLine();

            // Create fresh instance to save input in memory
            User user = new User(userid, username, email, password, userrole);
            
            // Adds the user to the excisting list
            users.Add(user);

            FileOperations fo = new FileOperations();
            // Calling the method from FileOperations.cs to write the List here to a CSV file
            fo.WriteUsersToCSV(users);
            
        }

现在输出到csv文件:

userid,username,email,password,userrole
1,Inkoop,inkoop@gimpies.nl,123,purchase
2,Verkoop,verkoop@gimpies.nl,123,sales
4,Beheer,beheer@gimpies.nl,123,admin
3,Bas,bas@bas.nl,123,sales

它添加了用户,但现在当添加新用户 (Bas) 时,最后一个用户获得不同的用户 ID。

这是我的用户 class 可以肯定的是:

namespace GimpiesConsoleOOcsvListUI
{
    public class User
    {
        // Constructor
        public User(int userid, string username, string email, string password, string userrole)
        {
            _UserId = userid;
            _UserName = username;
            _Email = email;
            _Password = password;
            _UserRole = userrole;
        }
        private int _UserId;
        private string _UserName;
        private string _Email;
        private string _Password;
        private string _UserRole;

        public int userid
        {
            get { return _UserId; }
            set { _UserId = value; } 
        }
        public string username
        {
            get { return _UserName; }
            set { _UserName = value; }
        }

        public string email
        {
            get { return _Email; }
            set { _Email = value; }
        }

        public string password
        {
            get { return _Password; }
            set { _Password = value; }
        }

        public string userrole
        {
            get { return _UserRole; }
            set { _UserRole = value; }
        }
        
    }
}

更新二:

我尝试了下面评论中的建议。但我现在在我的 csv 文件中得到了这个输出。与我 Console.WriteLine 在内存中显示列表时相同:

userid,username,email,password,userrole
1,Inkoop,inkoop@gimpies.nl,123,purchase
2,Verkoop,verkoop@gimpies.nl,123,sales
5,Beheer,beheer@gimpies.nl,123,admin
3,Bas,bas@bas.bl,123,admin
4,Tim,tim@tim.nl,123,sales

如您所见,新添加的用户 Bas 和 Tim 的用户 ID 为 3 和 4。现有用户 Beheer 从用户 ID 3 变为用户 ID 5。所以 userid++ 有效,但不是我想要的。

三个默认用户(Inkoop、Verkoop 和 Beheer)应保持用户 ID 1、2 和 3。新用户应从 4 继续...

我注册新用户的方法:

public void Register(List<User> users)
        {
            
            User usr = users.OrderByDescending(u => u.userid).FirstOrDefault();
            
            int userid = (usr == null ? 1 : usr.userid++);

            // Get user input
            Console.WriteLine("Enter username:");
            string username = Console.ReadLine();

            Console.WriteLine("Enter email:");
            string email = Console.ReadLine();

            Console.WriteLine("Enter password:");
            string password = Console.ReadLine();

            Console.WriteLine("Enter userrole (typ admin, purchase or sales):");
            string userrole = Console.ReadLine();

            // Create fresh instance to save input in memory
            User user = new User(userid, username, email, password, userrole);
            
            // Adds the user to the excisting list
            users.Add(user);

            FileOperations fo = new FileOperations();
            // Calling the method from FileOperations.cs to write the List here to a CSV file
            fo.WriteUsersToCSV(users);
            
        }

我写csv文件的方法:

public void WriteUsersToCSV(List<User> users)
        {
            
            // overwrite the file each time; indicated by the `false` parameter
            using (var writer = new StreamWriter("users.csv", false))
            using (var csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                User usr = users.OrderBy(u => u.userid).FirstOrDefault();
                // csvWriter.Configuration.HasHeaderRecord = false; // commented out as we write the whole file every time including the header
                csvWriter.WriteRecords(users);
                Console.WriteLine("New user added to users.csv");
            }
        }

我认为由于列表中对象的定位以某种方式影响了 userid++...我还尝试将 users.Add 更改为 users.Insert(3, user)。但是显示了相同的结果。我错过了什么?

用户变量是 List<User>。您不能在此列表中搜索 UserId,它是每个用户的 属性。编译器无法理解传递给 LastIndexOf 的整数应该用于在列表中搜索具有该 ID 的用户。这正是编译器显示的错误的含义。

幸运的是,我们可以使用 Linq 来完成此类任务。所以搜索具有特定用户 ID 的用户很简单

 User usr = users.FirstOrDefault(u => u.UserId == 3);

这将 return 一个 User 实例,如果 userid = 3 存在于列表中,否则为 null。

但是在您的代码中您还需要更多东西。您需要知道最后插入的用户标识(或从文件重新加载),然后在将其分配给下一个用户之前递增该值。同样,在 Linq 命名空间中,我们可以找到另一种可以帮助我们的方法

public void Register(List<User> users)
{
   User usr = users.OrderByDescending(u => u.UserID).FirstOrDefault();
   int nextUserId = (usr == null ? 1 : usr.UserId++);
   .....

这将按 UserId 降序排列用户序列,然后我们再次获取序列的第一个元素。现在为下一个用户增加用户 ID 是微不足道的。

这是解决我问题的答案:

int userid = (usr == null ? 1 : usr.userid + 1);