【问题标题】:How can I update specific element in List<T>?如何更新 List<T> 中的特定元素?
【发布时间】:2021-04-17 07:54:26
【问题描述】:

我正在编写一个 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。 然后程序将显示每个属性,如UserIDAccountTypeStatus。如果用户没有为任何属性输入任何输入,则信息保持不变。 我试图将来自用户的输入保存在new Customer() 对象中,但无法继续比较它或将其保存在我从文本文件中存储数据的List&lt;customers&gt; 中。 我怎样才能做到这一点?

【问题讨论】:

  • 欢迎来到 Stack Overflow。请通过tour 了解 Stack Overflow 的工作原理,并阅读How to Ask 以了解如何提高问题的质量。然后查看help center,看看你可以问什么问题。请显示您尝试过的尝试以及您从尝试中得到的问题/错误消息。
  • 嗯,试试?这要么是一项任务,要么是一项工作:您应该能够自己完成这项工作。 SO 不是代码编写服务。我们可以帮助您解决问题,但您必须自己努力。

标签: c# generic-list


【解决方案1】:

这样的事情应该可以解决问题。

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

希望这会有所帮助:)

【讨论】:

  • 请阅读this,尤其是回答部分。
【解决方案2】:

您可以使用 Linq 查看此solution

int acNo = ReadAccountNumber();
IEnumerable<Customers> results = myList.Where(c => c.AccountNo == acNo);

如果您确定AccountNo 是唯一的,那么results 将只包含一个元素。如果存在,您可以更新第一个元素。

Customers cust = myList.First(c => c.AccountNo == acNo);
cust?.Name = newName;

【讨论】:

    猜你喜欢
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2021-06-19
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多