从dataTable中删除包含空值的行

时间:2013-07-04 07:49:33

标签: c# datatable

我有一个包含7800行的DataTable,每行包含3列,如果第二列为null,则可能有Null值我正在删除整行,问题是即使我删除了行,DataTable仍然包含相同的行行号的数量是7800

代码:

 string query = "Select STORE_NAME, STORE_LATITUDE, STORE_LONGTITUDE "
  +" From stores inner join contact_information on stores.STORE_ID=contact_information.CONTACT_ID "
    +" where CONTACT_TYPE_ID=1 "
      +" AND CONTACT_COUNTRY_ID="+Country
         +" AND CONTACT_CASA_ID="+Casa
            +" AND CONTACT_TOWN_ID="+Town;
    DataTable dt = new SQLHelper(SQLHelper.ConnectionStrings.KernelConnectionString).getQueryResult(query);
    dt = removeNullColumnFromDataTable(dt);

功能:

    public static DataTable removeNullColumnFromDataTable(DataTable dt)
   {
    for (int i = dt.Rows.Count - 1; i >= 0; i--)
      {
       if (dt.Rows[i][1].ToString() == null)
           dt.Rows[i].Delete();
      }
     return dt;
   }

2 个答案:

答案 0 :(得分:7)

public static void RemoveNullColumnFromDataTable(DataTable dt)
{
    for (int i = dt.Rows.Count - 1; i >= 0; i--)
    {
        if (dt.Rows[i][1] == DBNull.Value)
            dt.Rows[i].Delete();
    }
    dt.AcceptChanges();
}

答案 1 :(得分:1)

您可以将第一行更改为此(对于sql server):

string query = "Select STORE_NAME, isnull(STORE_LATITUDE,'') as STORE_LATITUDE, STORE_LONGTITUDE "

并检查空字符串(如果字段类型为char,varchar ...等..)

dt.Rows[i][1].ToString() == ""

或使用isnull(STORE_LATITUDE,0)并检查零dt.Rows [i] [1] .ToString()==“0”如果字段类型是数字