Merge the value of the DataTable duplicate row in c

  • 2020-05-10 18:40:22
  • OfStack


            //DataTable Add the data 
            Hashtable ht = new Hashtable();
            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("id");
            dt.Columns.Add(dc);
            dc = new DataColumn("name");
            dt.Columns.Add(dc);
            dc = new DataColumn("values");
            dt.Columns.Add(dc);
            DataRow dr = dt.NewRow();
            dr["id"] = 1;
            dr["name"] = " zhang 3";
            dr["values"] = "A";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["id"] = 2;
            dr["name"] = " li 4";
            dr["values"] = "B";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["id"] = 3;
            dr["name"] = " zhang 3";
            dr["values"] = "C";
            dt.Rows.Add(dr);
            dataGridView1.DataSource = dt;
            // merge 
            for (int i = 0; i < dt.Rows.Count; i++ )
            {
                if (ht.ContainsKey(dt.Rows[i]["name"]))
                {
                    // Get the row index 
                    int index = (int)ht[dt.Rows[i]["name"]];
                    // For the recent 1 The value of the time ( The corresponding values)
                    string str = (string)dt.Rows[index]["values"];
                    // Joining together 
                    dt.Rows[index]["values"] = str + "|" + dt.Rows[i]["values"];
                    // Delete duplicate lines 
                    dt.Rows.RemoveAt(i);
                    // Adjust index subtraction 1
                    i--;
                }
                else
                {
                    // Save the name and the row index 
                    ht.Add(dt.Rows[i]["name"], i);
                }
} 


Related articles: