亲宝软件园·资讯

展开

合并DataTable重复行 c#中合并DataTable重复行的值

人气:3
想了解c#中合并DataTable重复行的值的相关内容吗,在本文为您仔细讲解合并DataTable重复行的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:合并,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);
                }

}

加载全部内容

相关教程
猜你喜欢
用户评论