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

标签 c# list csv auto-increment indexof

我使用以下方法(注册)的目标是当管理员填写用户详细信息并将其全部保存在列表中时自动增加用户 ID,最终将新添加的用户写入 csv 文件。每次加载应用程序时都会读取 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,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="056c6b6e6a6a7545626c68756c60762b6b69" rel="noreferrer noopener nofollow">[email protected]</a>,123,purchase
2,Verkoop,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f293a2d3430302f1f3836322f363a2c713133" rel="noreferrer noopener nofollow">[email protected]</a>,123,sales
3,Beheer,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="214344494444536146484c514844520f4f4d" rel="noreferrer noopener nofollow">[email protected]</a>,123,admin
4,Bas,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bad8dbc9fad8dbc994d4d6" rel="noreferrer noopener nofollow">[email protected]</a>,123,admin
4,Tim,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3a7babe93a7babefdbdbf" rel="noreferrer noopener nofollow">[email protected]</a>,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,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="234a4d484c4c5363444a4e534a46500d4d4f" rel="noreferrer noopener nofollow">[email protected]</a>,123,purchase
2,Verkoop,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbbdaeb9a0a4a4bb8baca2a6bba2aeb8e5a5a7" rel="noreferrer noopener nofollow">[email protected]</a>,123,sales
4,Beheer,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f7f0fdf0f0e7d5f2fcf8e5fcf0e6bbfbf9" rel="noreferrer noopener nofollow">[email protected]</a>,123,admin
3,Bas,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e2c2f3d0e2c2f3d602022" rel="noreferrer noopener nofollow">[email protected]</a>,123,sales

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

这是我的 User 类:

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 在内存中显示列表时相同:

userid,username,email,password,userrole
1,Inkoop,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fb92959094948bbb9c92968b929e88d59597" rel="noreferrer noopener nofollow">[email protected]</a>,123,purchase
2,Verkoop,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2c3f283135352a1a3d33372a333f29743436" rel="noreferrer noopener nofollow">[email protected]</a>,123,sales
5,Beheer,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8e898489899eac8b85819c85899fc28280" rel="noreferrer noopener nofollow">[email protected]</a>,123,admin
3,Bas,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcdeddcffcdeddcf92ded0" rel="noreferrer noopener nofollow">[email protected]</a>,123,admin
4,Tim,<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3135182c3135763634" rel="noreferrer noopener nofollow">[email protected]</a>,123,sales

正如您所看到的,新添加的用户 Bas 和 Tim 将获得 userid 3 和 4。现有用户 Beheer 从 userid 3 变为 userid 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)。但显示了相同的结果。我错过了什么?

最佳答案

users 变量是 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 是很简单的。

关于c# - 如何通过用户输入(控制台应用程序)使用 C# 中的列表使用 IndexOf 方法自动递增 int userid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63512866/

相关文章:

ruby-on-rails - Rails 事件管理 csv 输出所有结果而不是选择

python-2.7 - 计算 CSV 行中的特定值

c# - 在C#和WPF中学习自动化测试的资源

c# - WCF .net 4.0 HTTP 基本身份验证

list - Lisp 列表操作问题

python - 循环遍历相应的行并更改数据框的值

c# - 在 MVC 中将 ASP.NET Identity 与我自己的实体结合使用

c# - 我应该如何比较两个列表中的值?

python - 用字符串枚举列表会给出错误的结果

Java 使用 lambda 谓词查找列表中元素的索引