简体   繁体   English

从CSV文件读取C#

[英]C# reading from a CSV file

I am trying to read from a csv file with the following code - 我正在尝试使用以下代码从csv文件读取-

        List<Person> people = new List<Person>();
        Person personToAdd = new Person();


        TextFieldParser parser = new TextFieldParser(@"C:\Users\user\Documents\Book1.csv");
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");
        while (!parser.EndOfData)
        {
            //Processing row
            string[] fields = parser.ReadFields();
            int counter = 0;

            foreach (string field in fields)
            {
                personToAdd.username = fields[0];
                personToAdd.firstName = fields[1];
                personToAdd.lastName = fields[2];
                personToAdd.email = fields[3];
                personToAdd.password = fields[4];
                personToAdd.role = fields[5];

                people.Add(personToAdd);
            }
        }
        parser.Close();

This code does read from the CSV file, but every entry in my people object contains the last entry that was listed in the CSV file. 该代码确实从CSV文件中读取,但是我的人员对象中的每个条目都包含CSV文件中列出的最后一个条目。 I'm sure this is a fairly simple change, but I'm quite new to this and can't figure it out. 我确信这是一个相当简单的更改,但是我对此很陌生,无法解决。

You should move the creation and initialization of the Person instance inside the while loop and remove the foreach loop. 您应该在while循环内移动Person实例的创建和初始化,并删除foreach循环。 The fields are reloaded at every while loop 在每个while循环中重新加载字段

...
while (!parser.EndOfData)
{
    // Loading the fields of a Person 
    string[] fields = parser.ReadFields();

    // Starting the process that creates a new Person 
    Person personToAdd = new Person();
    personToAdd.username = fields[0];
    personToAdd.firstName = fields[1];
    personToAdd.lastName = fields[2];
    personToAdd.email = fields[3];
    personToAdd.password = fields[4];
    personToAdd.role = fields[5];

    // Adding the new person to the list
    people.Add(personToAdd);

} .... } ....

In your example above, the creation of the instance is outside the loop. 在上面的示例中,实例的创建在循环之外。 Inside the loop you change the properties of the same instance and read it at every loop. 在循环内部,您可以更改同一实例的属性,并在每个循环中读取它。 When you exit the loop all the items addeded point to the same instance with the value set for the last line read from the file 退出循环时,所有添加的项目都指向同一实例,并为从文件中读取的最后一行设置了值

Instead creating a new instance inside the loop guarantees that every item added to the list is a different one with different data in its properties. 而是在循环内创建一个新实例,以确保添加到列表的每个项目都是其属性具有不同数据的不同项目。

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

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