Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IList.Add() overwriting existing data [duplicate]

Tags:

c#

ilist

I'm facing a problem adding data to an IList but the problem is each time I added data the existing data is overwritten with the current one my code is given below:

Test test = new Test();
IList<Test> myList = new List<Test>();

foreach (DataRow dataRow in dataTable.Rows)
{
     test.PatientID = Convert.ToInt64(dataRow.ItemArray[0]);
     test.LastName = dataRow.ItemArray[1].ToString();
     test.FirstName = dataRow.ItemArray[2].ToString();
     myList.Add(test);
}

What's the reason behind this?

like image 627
Optimus Avatar asked Oct 03 '13 10:10

Optimus


1 Answers

move test object creation inside the loop

IList<Test> myList = new List<Test>();

foreach (DataRow dataRow in dataTable.Rows)
{   Test test =new Test();
    test.PatientID = Convert.ToInt64(dataRow.ItemArray[0]);
    test.LastName = dataRow.ItemArray[1].ToString();
    test.FirstName = dataRow.ItemArray[2].ToString();
    myList.Add(test);
 }

what you currently doing is updating same instant of test inside the loop and add the same again and again..

like image 84
Damith Avatar answered Oct 07 '22 08:10

Damith