首页 > 解决方案 > 如何更新列表中的特定元素?

问题描述

我正在编写一个 C# 控制台应用程序,其中有一个 Customer 类,如下所示:

    public class Customers
    {
        public string Name { get; set; }
        public string UserID { get; set; }
        public int Pin { get; set; }
        public int AccountNo { get; set; }
        public string AccountType { get; set; }
        public int Balance { get; set; }
        public string Status { get; set; }
    }

我将客户数据存储在如下文本文件(“Customers.txt”)中:

[
    {"Name":"Jack Willson","UserID":"Jack21","Pin":12345,"AccountNo":1,"AccountType":"Savings","Balance":2000,"Status":"Active"},
    {"Name":"Mary Poppins","UserID":"mary8912","Pin":67890,"AccountNo":2,"AccountType":"Savings","Balance":4567,"Status":"Active"},
    {"Name":"Harry Potter","UserID":"Harry45","Pin":12345,"AccountNo":4,"AccountType":"Savings","Balance":12000,"Status":"Active"}
]

我正在阅读此文件:

List<Customers> list = ReadFile<Customers>("Customers.txt");

我希望根据用户输入更新特定的客户字段。如果用户将字段输入留空,则字段信息保持不变。

该程序将要求用户输入 AccountNo他希望更新的信息。然后程序将显示每个属性,如UserID, AccountType, Status。如果用户没有为任何属性输入任何输入,则信息保持不变。我试图将用户的输入保存在new Customer()对象中,但无法继续比较它或将其保存在List<customers>我从文本文件中存储数据的位置。我怎样才能做到这一点?

标签: c#generic-list

解决方案


像这样的东西应该可以解决问题。

var accountNum = 2; //I'm going to assume you get this from Console.ReadLine() and validate it.

//Find the customer with that account number...
var query = list.Where(c => c.AccountNo == accountNum);

if (!query.Any()
    Console.WriteLine("Customer not found.");
    
var customer = query.First();

//Now you can manipulate the customer object as you please
//In your situation I think you want to loop through the properties they can change and set them.
customer.Name = "Some new name";
customer.Pin = 1234;

//Save the updated information back to the text file however you currently do this

希望这会有所帮助:)


推荐阅读