简体   繁体   中英

C# reading from a CSV file

I am trying to read from a csv file with the following code -

        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. 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. The fields are reloaded at every while loop

...
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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