其中要避免目標庫插入重復數據。這重復數據可能是源數據庫本身就有重復數據,還有就是已經插入避免重復插入。
過濾自身重復數據解決方案
第一種:采用DataView.ToTable()方法
DataView.ToTable 方法
重載列表
名稱 | 說明 |
---|---|
DataView.ToTable () | 根據現有 DataView 中的行,創建並返回一個新的 DataTable。 由 .NET Compact Framework 支持。 |
DataView.ToTable (String) | 根據現有 DataView 中的行,創建並返回一個新的 DataTable。 由 .NET Compact Framework 支持。 |
DataView.ToTable (Boolean, String[]) | 根據現有 DataView 中的行,創建並返回一個新的 DataTable。 由 .NET Compact Framework 支持。 |
DataView.ToTable (String, Boolean, String[]) | 根據現有 DataView 中的行,創建並返回一個新的 DataTable。 由 .NET Compact Framework 支持。 |
實例代碼
public static DataTable Distinct(DataTable dt, string[] filedNames) { DataView dv = dt.DefaultView; DataTable DistTable = dv.ToTable("Dist", true, filedNames); return DistTable; }
第二種方法:循環遍歷+DataTable.Select()
利用for循環遍歷DataTable的數據行,利用DataTable.Select 方法判斷是否重復,如果重復,則利用DataTable.Rows.RemoveAt(Index)刪除重復的那一行。
具體看代碼。
代碼示例
public DataTable GetDistinctSelf(DataTable SourceDt, string filedName) { for (int i = SourceDt.Rows.Count - 2; i > 0; i--) { DataRow[] rows = SourceDt.Select(string.Format("{0}='{1}'", filedName, SourceDt.Rows[i][filedName])); if (rows.Length > 1) { SourceDt.Rows.RemoveAt(i); } } return SourceDt; }
第三種方法
利用雙循環遍歷(不推薦)
public DataTable GetDistinctSelf(DataTable SourceDt, string filedName) { for (int i = SourceDt.Rows.Count - 2; i > 0; i--) { string title = SourceDt.Rows[0][filedName].ToString(); for (int j = i + 1; j > 0; i--) { if (SourceDt.Rows[j][filedName].ToString() == title) { SourceDt.Rows.RemoveAt(i); } } } return SourceDt; }