从DataRow添加项目到列表

时间:2016-11-16 10:16:38

标签: c# list datarow

我有以下代码将DataTable行复制到我的Object中。但它每次都会用新行覆盖以前添加的列表项。我的代码出了什么问题?

DataTable dt = GetDataTableByIndex(data, 1);
if (dt != null && dt.Rows.Count > 0)
{
   if (dt != null && dt.Rows.Count > 0)
   {
      providerQualification.ProviderDetails = new List<ProviderDetail>();
      ProviderDetail providerDetail = new ProviderDetail();
      foreach (DataRow row in dt.Rows)
      {
          providerDetail.ProviderName = row["Provider Name"].ToString();
          providerDetail.QualificationTime = row["Qualify Time (Sec.)"].ToString();
          providerDetail.ServiceableOffers = row["Total Serviceable Offers"].ToString();
          providerQualification.ProviderDetails.Add(providerDetail);
      }
  }
}

1 个答案:

答案 0 :(得分:2)

试试这个,

DataTable dt = GetDataTableByIndex(data, 1);
if (dt != null && dt.Rows.Count > 0)
{
      providerQualification.ProviderDetails = new List<ProviderDetail>();
      ProviderDetail providerDetail;
      foreach (DataRow row in dt.Rows)
      {    
          providerDetail = new ProviderDetail();
          providerDetail.ProviderName = row["Provider Name"].ToString();
          providerDetail.QualificationTime = row["Qualify Time (Sec.)"].ToString();
          providerDetail.ServiceableOffers = row["Total Serviceable Offers"].ToString();
          providerQualification.ProviderDetails.Add(providerDetail);
      }
  }