C#中合併DataTable中重複行

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;


public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        //DataRow dr = new DataRow();
        dt.Columns.Add("C1");
        dt.Columns.Add("C2");
        dt.Columns.Add("C3");
        dt.Columns.Add("C4");
        dt.Rows.Add(new string[4]{ "A1", "A2", "a" ,"1"});
        dt.Rows.Add(new string[4] { "A1", "A2", "b", "1" });
        dt.Rows.Add(new string[4] { "A1", "A2", "c", "1" });
        dt.Rows.Add(new string[4] { "B1", "B2", "a", "1" });


        CompressTable(dt);
        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();


    }
    static void CompressTable(DataTable table)
    {
        Dictionary<string, DataRow> dict = new Dictionary<string, DataRow>(); //這個字典用於查找第一第二列相同的項目    
        List<DataRow> removeRows = new List<DataRow>(); //這個List 存儲需要刪除的重複行          
        foreach (DataRow row in table.Rows)
        {
            string key = row[0].ToString() + ";" + row[1].ToString();
            DataRow row1; 
            if (dict.TryGetValue(key, out row1))
            {                    //如果找到重複的行,將第三列和第一個重複行的第4列合併                    
                if (row1[3] == DBNull.Value)
                {
                    row1[3] = row[3].ToString();
                    row1[2] = row[2].ToString();
                }
                else
                {
                    row1[2] = row1[2].ToString() + ";" + row[2].ToString();
                    row1[3] = int.Parse(row1[3].ToString())+ int.Parse(row[3].ToString());
                } removeRows.Add(row); //將這一行加入要刪除的行列表中               
            }
            else
            {
                dict.Add(key, row);
            }
        }            //刪除重複的行          
        foreach (DataRow row in removeRows) { table.Rows.Remove(row); }
    }
}


運行效果截圖:



發佈了24 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章