為了解決將多個DataTable 組合成一個表格的問題,我們建議一個有效的方法來有效處理改變列結構和行對齊。
以下C# 程式碼片段提供簡單的方法:
public static DataTable MergeTables(IList<DataTable> tables, string primaryKeyColumn) { if (!tables.Any()) throw new ArgumentException("Tables must not be empty", "tables"); if (primaryKeyColumn != null) foreach (DataTable t in tables) if (!t.Columns.Contains(primaryKeyColumn)) throw new ArgumentException("All tables must have the specified primarykey column " + primaryKeyColumn, "primaryKeyColumn"); if (tables.Count == 1) return tables[0]; DataTable table = new DataTable("TblUnion"); table.BeginLoadData(); // Turns off notifications, index maintenance, and constraints while loading data foreach (DataTable t in tables) { table.Merge(t); // same as table.Merge(t, false, MissingSchemaAction.Add); } table.EndLoadData(); if (primaryKeyColumn != null) { // join rows with repeating primary key columns var pkGroups = table.AsEnumerable() .GroupBy(r => r[primaryKeyColumn]); var dupGroups = pkGroups.Where(g => g.Count() > 1); foreach (var grpDup in dupGroups) { // use first row and modify it DataRow firstRow = grpDup.First(); foreach (DataColumn c in table.Columns) { if (firstRow.IsNull(c)) { DataRow firstNotNullRow = grpDup.Skip(1).FirstOrDefault(r => !r.IsNull(c)); if (firstNotNullRow != null) firstRow[c] = firstNotNullRow[c]; } } // remove all but first row var rowsToRemove = grpDup.Skip(1); foreach(DataRow rowToRemove in rowsToRemove) table.Rows.Remove(rowToRemove); } } return table; }
要使用MergeTables 方法,請依照以下步驟操作:
考慮以下範例DataTables:
DataTable1 (Columns: c1, c2, c3, c4) | c1 | c2 | c3 | c4 | |---|---|---|---| | 1 | 8500 | abc | A | | 2 | 950 | cde | B | | 3 | 150 | efg | C | | 4 | 850 | ghi | D | | 5 | 50 | ijk | E | DataTable2 (Columns: c1, c5, c6, c7) | c1 | c5 | c6 | c7 | |---|---|---|---| | 1 | 7500 | klm | F | | 2 | 900 | mno | G | | 3 | 150 | opq | H | | 4 | 850 | qrs | I | | 5 | 50 | stu | J | DataTable3 (Columns: c1, c8, c9, c10) | c1 | c8 | c9 | c10 | |---|---|---|---| | 1 | 7500 | uvw | K | | 2 | 900 | wxy | L | | 3 | 150 | yza | M | | 4 | 850 | ABC | N | | 5 | 50 | CDE | O |
要合併這三個表,我們可以呼叫MergeTables 方法,如下所示:
var tables = new[] { DataTable1, DataTable2, DataTable3 }; DataTable mergedTable = MergeTables(tables, "c1");
mergedTable將包含三個輸入表中的所有行,其中由公共主鍵列「c1」對齊的列。行中的任何缺失值將從具有相同主鍵值的第一個非空白行填入。
以上是如何在 C# 中有效地將具有不同架構的多個 DataTable 合併到單一 DataTable 中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!