挑戰:
合併多個具有不同列定義和行數的DataTable,同時確保對齊並保持資料完整性可以
解決方案:
要克服此問題並建立單一綜合資料表,您可以採用以下自訂方法:
public static DataTable MergeAll(this IList<DataTable> tables, String primaryKeyColumn) { // Validate arguments 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"); DataTable table = new DataTable("TblUnion"); // Disable data validation during bulk loading table.BeginLoadData(); // Merge all tables into the result table foreach (DataTable t in tables) table.Merge(t, false, MissingSchemaAction.Add); // End data validation table.EndLoadData(); // Handle duplicate primary keys (if specified) if (primaryKeyColumn != null) { // Group rows by primary key column var pkGroups = table.AsEnumerable().GroupBy(r => r[primaryKeyColumn]); // Identify groups with duplicate keys var dupGroups = pkGroups.Where(g => g.Count() > 1); // Combine data from duplicate rows into the first row of each group foreach (var grpDup in dupGroups) { // Use the first row and modify it to include data from other rows DataRow firstRow = grpDup.First(); foreach (DataColumn c in table.Columns) { if (firstRow.IsNull(c)) { // Find the first non-null row for the current column and copy its value DataRow firstNotNullRow = grpDup.Skip(1).FirstOrDefault(r => !r.IsNull(c)); if (firstNotNullRow != null) firstRow[c] = firstNotNullRow[c]; } } // Remove duplicate rows var rowsToRemove = grpDup.Skip(1); foreach (DataRow rowToRemove in rowsToRemove) table.Rows.Remove(rowToRemove); } } // Return the merged table return table; }
用法:
var tables = new[] { tblA, tblB, tblC }; DataTable TblUnion = tables.MergeAll("c1");
此方法提供了強大的合併解決方案資料表,處理資料對齊並保留關鍵資料。
以上是如何有效率地將多個不同結構的資料表合併到一個表中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!