c# - 如何更新列表中的特定元素?
问题描述
我正在编写一个 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>
我从文本文件中存储数据的位置。我怎样才能做到这一点?
解决方案
像这样的东西应该可以解决问题。
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
希望这会有所帮助:)
推荐阅读
- java - 如何在 Infinispan 中启用 JGroups 登录
- c# - c#为什么扩展方法是静态的并包装在静态类中
- pandas - 在 Pandas 中重新采样并进行线性插值
- laravel - Laravel 5.5,索引的默认路由不适用于资源控制器
- c++ - 在 C++ 中为方法调用自动插入括号
- css - 在 Angular 4 中导入材质设计布局网格
- sql - 在最后一分钟内选择行
- java - 什么是 DI 容器?
- c# - 如何在表格中显示列表
- xamarin - Xamarin OneSignal:尝试在项目“PushNotificationEx.Android”上安装所需的 android 组件时发生错误