c#中合并DataTable重复行的值
本文导语: 代码如下: //DataTable数据添加 Hashtable ht = new Hashtable(); DataTable dt = new DataTable(); DataColumn dc = new DataColumn("id"); dt.Columns.Add(dc); dc = ...
//DataTable数据添加
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"] = "张三";
dr["values"] = "A";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["id"] = 2;
dr["name"] = "李四";
dr["values"] = "B";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["id"] = 3;
dr["name"] = "张三";
dr["values"] = "C";
dt.Rows.Add(dr);
dataGridView1.DataSource = dt;
//合并
for (int i = 0; i < dt.Rows.Count; i++ )
{
if (ht.ContainsKey(dt.Rows[i]["name"]))
{
//获取行索引
int index = (int)ht[dt.Rows[i]["name"]];
//获取最近一次的值(对应values)
string str = (string)dt.Rows[index]["values"];
//拼接
dt.Rows[index]["values"] = str + "|" + dt.Rows[i]["values"];
//删除重复行
dt.Rows.RemoveAt(i);
//调整索引减1
i--;
}
else
{
//保存名称以及行索引
ht.Add(dt.Rows[i]["name"], i);
}
}