欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#中合并DataTable重复行的值

程序员文章站 2023-12-16 16:59:04
复制代码 代码如下:            //datatab...

复制代码 代码如下:

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

}

上一篇:

下一篇: