首页 > 解决方案 > 如何通过用户输入(控制台应用程序)在 C# 中使用带有 List 的 IndexOf 方法自动增加 int userid?

问题描述

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

这是发生用户输入以及我想自动增加用户 ID 的方法:

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。

这是我的用户类,以确保:

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

更新 2:

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

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。所以用户 ID++ 有效,但不是我想要的。

三个默认用户(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");
            }
        }

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

标签: c#listcsvauto-incrementindexof

解决方案


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

幸运的是,我们可以将 Linq 用于此类任务。因此,使用特定用户 ID 搜索用户很简单

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

如果它存在于列表中,这将返回一个具有该 userid = 3 的 User 实例,否则返回 null 。

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

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

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


推荐阅读