VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#教程之c#中合并DataTable重复行的值

代码如下:

            //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);
                }



相关教程