简体   繁体   English

为 C# 中的对象列表提供控制台输入

[英]Give console input for List of objects in C#

I want a program to write info about persons to a file in C#...so I have the following class我想要一个程序将有关人员的信息写入 C# 中的文件......所以我有以下 class

class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

    }

And the class that writes to the file is this one:写入文件的 class 是这个:

       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);
        }
    }

And the main method...主要方法...

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();

        }

And the elemnts that I am adding in the List are hard codded in the following method...我在列表中添加的元素在以下方法中被硬编码......

 public static void Elements(List<Person> persons)
        {

            persons.Add(new Person() { FirstName = "Cosmin", LastName = "Ionut" });
            persons.Add(new Person() { FirstName = "Bianca", LastName = "Elena" });
    
        }

So what I want is to be able to add those persons as a console input, not hard coded in a method所以我想要的是能够将这些人添加为控制台输入,而不是在方法中硬编码

One idea would be to write a method that gets the first and last name from console input and returns a new Person object.一个想法是编写一个方法,从控制台输入中获取名字和姓氏,并返回一个新的Person object。 Below I've added it as a static method on the Person class.下面我将它作为static方法添加到Person class 上。

I also added an instance method called AsCsvItem which returns the person in CSV format ( "FirstName, LastName" ), which will come in handy later.我还添加了一个名为AsCsvItem的实例方法,它以 CSV 格式( "FirstName, LastName" )返回人员,稍后会派上用场。

And finally I added a static SaveToFile method that will save a list of people to the specified file path in Csv format.最后我添加了一个static SaveToFile方法,它将人员列表保存到 Csv 格式的指定文件路径。

Note that these new methods could exist somewhere else, I just put them in the Person class for convenience:请注意,这些新方法可能存在于其他地方,为方便起见,我只是将它们放在Person class 中:

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);
    }
}

Then you can just call the FromConsoleInput method in a loop to populate a list of people, and the SaveToFile method to save them to the csv file.然后,您可以在循环中调用FromConsoleInput方法来填充人员列表,并调用SaveToFile方法将他们保存到 csv 文件中。 Below I'm using numPeople to determine how many people we should add:下面我使用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");

If you want a smaller change, I would do this:如果您想要较小的更改,我会这样做:

public static List<Person> GetElements()
{
    List<Person> persons = new List<Person>();
    do
    {
        var person = new Person();

        Console.Write("Enter first name: ");
        person.FirstName = Console.ReadLine();
        Console.Write("Enter last name: ");
        person.LastName = Console.ReadLine();
        persons.Add(person);

        Console.Write("Press Y to enter another person, other key to finish.");
    } while (Console.ReadKey().Key == ConsoleKey.Y);

    return persons;
}

The code is pretty straightforward.代码非常简单。 I wouldn't create the list in Main but instead let this method create and populate the list, so all actions related to creating the list are in one place.我不会在Main中创建列表,而是让此方法创建并填充列表,因此与创建列表相关的所有操作都在一个地方。 Furthermore, methods are usually verbs to clearly state what they do.此外,方法通常是动词,以明确 state 他们做了什么。 With void Elements(List<Person>) you can't guess what it does at all.使用void Elements(List<Person>)你根本猜不到它的作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM