r mk r r mk r - 2 months ago 11
C# Question

Adding data to a property of type List<>

I am extracting data from an excel sheet and placing that into class properties.
In the below shown piece of code I am trying to add data into a property of type

List<>
. It executes without errors but the
List<>
count is 1 all the time.
as shown in the below example the for loop runs 5 times but the rah.rahTermDate count is 1 after existing the for loop.

for (int i = 0; i < 5; i++)
{
RawACAHireTermDates rahd = new RawACAHireTermDates();
rahd.RawHireDate = Convert.ToDateTime(GetCellValue(GetCell(sheetData, Cells[i, k], j), workbookPart, false, true));
rahd.RawTermDate = Convert.ToDateTime(GetCellValue(GetCell(sheetData, Cells[i, (k + 1)], j), workbookPart, false, true));
rah.rahTermDate = new List<RawACAHireTermDates> { rahd };
// rah.rahTermDate.Add(rahd);
}


Business object :

public class MasterClientGroupSheetData
{
public class RawACAHireTermDates
{
public DateTime? RawHireDate { get; set; }
public DateTime? RawTermDate { get; set; }
}

public class RawACAHireTermEmployee
{
...........
public List<RawACAHireTermDates> rahTermDate { get; set; }
}
}

Jay Jay
Answer

This line is the culprit:

rah.rahTermDate = new List<RawACAHireTermDates> { rahd };

Every time the loop runs, you are setting a NEW list to rah.rahTermDate.

Your code should be more like this:

//before the loop, declare a new List
rah.rahTermDate = new List<RawACAHireTermDates>();

for (int i = 0; i < 5; i++)
  {                  
    RawACAHireTermDates rahd = new RawACAHireTermDates();
    rahd.RawHireDate = Convert.ToDateTime(GetCellValue(GetCell(sheetData, Cells[i, k], j), workbookPart, false, true));
    rahd.RawTermDate = Convert.ToDateTime(GetCellValue(GetCell(sheetData, Cells[i, (k + 1)], j), workbookPart, false, true));

    //add to the existing list...
    rah.rahTermDate.Add(rahd);               
  }
Comments