c# - 为 C# 中的对象列表提供控制台输入
问题描述
我想要一个程序将有关人员的信息写入 C# 中的文件...所以我有以下课程
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
写入文件的类是这个:
class Adding
{
public static void AddedPersons(List<Person> persons,string path)
{
List<string> content = new List<string>();
content.Add("FirstName , LastName");
foreach (var person in persons)
{
content.Add($"{person.FirstName}, {person.LastName}");
}
System.IO.File.WriteAllLines(path,content);
}
}
主要方法...
static void Main(string[] args)
{
List<Person> persons = new List<Person>();
string path = @"C:\Users\cosmi\Desktop\Citire\Test.csv";
Elements(persons);
Adding.AddedPersons(persons, path);
Console.ReadLine();
}
我在列表中添加的元素在以下方法中被硬编码......
public static void Elements(List<Person> persons)
{
persons.Add(new Person() { FirstName = "Cosmin", LastName = "Ionut" });
persons.Add(new Person() { FirstName = "Bianca", LastName = "Elena" });
}
所以我想要的是能够将这些人添加为控制台输入,而不是在方法中硬编码
解决方案
一个想法是编写一个从控制台输入获取名字和姓氏并返回一个新Person
对象的方法。下面我将它添加为类的static
方法Person
。
我还添加了一个名为的实例方法AsCsvItem
,它以 CSV 格式 ( "FirstName, LastName"
) 返回人员,稍后会派上用场。
最后我添加了一个static
SaveToFile
方法,它将人员列表以 Csv 格式保存到指定的文件路径。
请注意,这些新方法可能存在于其他地方,Person
为了方便起见,我只是将它们放在类中:
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public static Person FromConsoleInput()
{
var person = new Person();
Console.Write("Enter first name: ");
person.FirstName = Console.ReadLine();
Console.Write("Enter last name: ");
person.LastName = Console.ReadLine();
return person;
}
public string AsCsvItem()
{
return $"{FirstName} , {LastName}";
}
public static void SaveToFile(List<Person> people, string path)
{
// Create a list with the column headers
List<string> content = new List<string> {"FirstName , LastName"};
// Add a line for each person
content.AddRange(people.Select(person => person.AsCsvItem()));
// Save it to the file path
File.WriteAllLines(path, content);
}
}
然后,您可以FromConsoleInput
在循环中调用该方法来填充人员列表,以及将SaveToFile
其保存到 csv 文件的方法。下面我numPeople
用来确定我们应该添加多少人:
var numPeople = 2;
var people = new List<Person>();
for (var i = 0; i < numPeople; i++)
{
Console.WriteLine($"Enter person #{i + 1} info:");
people.Add(Person.FromConsoleInput());
}
Person.SaveToFile(people, @"c:\temp\people.csv");
推荐阅读
- intellij-idea - 如何防止焦点缠绕?
- r - 如何测试函数的参数是字符串还是对象
- javascript - 使用 Javascript 将值从 php 获取到 ajax 请求
- fiware - 我必须为 Keyrock Idm 上的每个 pep 代理注册一个应用程序吗?
- android - Android 上的 Koin Injection Stackover 流错误。不确定如何重构以停止此问题,寻求帮助
- amazon-web-services - AWS Step Function 同步任务令牌
- python - 未定义名称“netCDF4”-RStudio 中的 python
- reactjs - Redux chrome 扩展显示“未找到商店”
- r - 在x轴上绘制多列作为R中的系列
- java - Rabbitmq 处理消息后等待