list replacing all previous elements

前端 未结 1 778
南方客
南方客 2021-01-23 06:55

I have a list of type Person. When I create the list of people it replaces the previous list element\'s information with the current one. I have read about this being the proble

相关标签:
1条回答
  • 2021-01-23 07:00

    You need to move the initialization of

    Person tempPerson = new Person();
    

    into the loop

            string[] personArray;
    
            List<Person> people = new List<Person>();
            foreach (string line in lines)//lines are the people from file, it is correct
            {
              personArray = line.Split(',');
              if (personArray.Length == 2)
              {
               Person tempPerson = new Person();
               tempPerson.Name = personArray[0];
               tempPerson.Address = personArray[1];
               people.Add(tempPerson);
              }
            }
    

    Otherwise you are changing the properties of the same object.

    0 讨论(0)
提交回复
热议问题