需求:給定一個 DataTable,依某欄位(如身分證字號)去除重複列,並保持原資料表結構(欄位、型別)不變。以下提供一個通用方法:
/// <summary>
/// 取得指定欄位不重複的新 DataTable
/// </summary>
private DataTable GetDistinctTable(DataTable dt, string colName) {
if (dt.Rows.Count <= 1) return dt;
// 1. 取得去重後的鍵值集合
DataView dv = dt.DefaultView;
DataTable distinctKeys = dv.ToTable(true, colName); // distinct=true
// 2. 建立同結構的空表
DataTable result = dv.ToTable();
result.Clear();
// 3. 依鍵值逐筆撈取第一筆完整資料加入結果
foreach (DataRow keyRow in distinctKeys.Rows) {
string keyVal = keyRow[0]?.ToString();
if (string.IsNullOrEmpty(keyVal)) continue;
DataRow[] matches = dt.Select($"{colName}='{keyVal}'");
if (matches.Length > 0) {
result.Rows.Add(matches[0].ItemArray);
}
}
return result;
}
DataView.ToTable(true, colName) 可直接產生去重鍵值表。Select 篩選原表,取第一筆(matches[0])保留原始資料完整性。ItemArray 一次複製整列所有欄位值,效能優於逐欄位指派。try-catch 防禦式寫法,避免單筆錯誤中斷整體流程。