挑战:
合并多个具有不同列定义和行数的 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中文网其他相关文章!