首页 > 解决方案 > 为 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" });
    
        }

所以我想要的是能够将这些人添加为控制台输入,而不是在方法中硬编码

标签: c#listgenerics

解决方案


一个想法是编写一个从控制台输入获取名字和姓氏并返回一个新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");

推荐阅读