首页 > 代码库 > 取两个DataTable的交集,删除重复数据

取两个DataTable的交集,删除重复数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/// <summary>
        /// 取两个DataTable的交集,删除重复数据
        /// </summary>
        /// <param name="sourceDataTable">源DataTable</param>
        /// <param name="targetDataTable">目标DataTable</param>
        /// <param name="primaryKey">两个表的主键</param>
        /// <returns>合并后的表</returns>
        public static DataTable Merge(DataTable sourceDataTable, DataTable targetDataTable, string primaryKey)
        {
            if (sourceDataTable != null || targetDataTable != null || !sourceDataTable.Equals(targetDataTable))
            {
                sourceDataTable.PrimaryKey = new DataColumn[] { sourceDataTable.Columns[primaryKey] };
                DataTable dt = targetDataTable.Copy();
                foreach (DataRow tRow in dt.Rows)
                {
                    //拒绝自上次调用 System.Data.DataRow.AcceptChanges() 以来对该行进行的所有更改。
                    //因为行状态为DataRowState.Deleted时无法访问ItemArray的值
                    tRow.RejectChanges();
                    //在加载数据时关闭通知、索引维护和约束。
                    sourceDataTable.BeginLoadData();
                    //查找和更新特定行。如果找不到任何匹配行,则使用给定值创建新行。
                    DataRow temp = sourceDataTable.LoadDataRow(tRow.ItemArray, true);
                    sourceDataTable.EndLoadData();
                    sourceDataTable.Rows.Remove(temp);
                }
            }
            sourceDataTable.AcceptChanges();
            return sourceDataTable;
        }