将数据添加到List<>类型的属性中

时间:2016-09-20 18:09:23

标签: c# collections

我从excel表中提取数据并将其放入类属性中。 在下面显示的代码段中,我尝试将数据添加到类型List<>的属性中。它执行时没有错误,但List<>计数始终为1。 如下例所示,for循环运行5次,但在存在for循环后rah.rahTermDate计数为1。

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);               
  }

业务对象:

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; }
    }
}

4 个答案:

答案 0 :(得分:5)

此代码在每次迭代时重新初始化List并丢失以前的数据。

public Response upload(@Multipart("id") int Id, @Multipart("file") Attachment attachment) {

您应该在rah.rahTermDate = new List<RawACAHireTermDates> { rahd };循环之外定义列表,然后使用for

向其添加项目

答案 1 :(得分:3)

您正在循环中重新创建列表。在循环外创建一次:

{{1}}

答案 2 :(得分:1)

每次迭代都会创建新列表 rah.rahTermDate = new List<RawACAHireTermDates> { rahd }; 它只包含一个项目,处理相同的迭代。 要修复此问题,请在循环外定义列表,在循环中将元素添加到列表中,并在for循环后分配rah.rahTermDate

答案 3 :(得分:1)

这条线是罪魁祸首:

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

每次循环运行时,您都会将新列表设置为rah.rahTermDate

您的代码应该更像这样:

//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);               
  }