What is the best way to remove duplicates from a datatable?

前端 未结 12 2078
醉酒成梦
醉酒成梦 2021-01-02 13:23

I have checked the whole site and googled on the net but was unable to find a simple solution to this problem.

I have a datatable which has about 20 columns and 10K

12条回答
  •  南笙
    南笙 (楼主)
    2021-01-02 14:20

    This is a very simple code which doesnot require linq nor individual columns to do the filter. If all the values of columns in a row are null it will be deleted.


        public DataSet duplicateRemoval(DataSet dSet) 
    {
        bool flag;
        int ccount = dSet.Tables[0].Columns.Count;
        string[] colst = new string[ccount];
        int p = 0;
    
        DataSet dsTemp = new DataSet();
        DataTable Tables = new DataTable();
        dsTemp.Tables.Add(Tables);
    
        for (int i = 0; i < ccount; i++)
        {
            dsTemp.Tables[0].Columns.Add(dSet.Tables[0].Columns[i].ColumnName, System.Type.GetType("System.String"));
        }
    
        foreach (System.Data.DataRow row in dSet.Tables[0].Rows)
        {
            flag = false;
            p = 0;
            foreach (System.Data.DataColumn col in dSet.Tables[0].Columns)
            {
                colst[p++] = row[col].ToString();
                if (!string.IsNullOrEmpty(row[col].ToString()))
                {  //Display only if any of the data is present in column
                    flag = true;
                }
            }
            if (flag == true)
            {
                DataRow myRow = dsTemp.Tables[0].NewRow();
                //Response.Write("");
                for (int kk = 0; kk < ccount; kk++)
                {
                    myRow[kk] = colst[kk];         
    
                    // Response.Write("" + colst[kk] + "");
                }
                dsTemp.Tables[0].Rows.Add(myRow);
            }
        } return dsTemp;
    }
    

    This can even be used to remove null data from excel sheet.

提交回复
热议问题