Since this question arose in one of the comments, if the only relation between two tables is the index of a DataRow in the table and you want to merge both tables according to the index:public static DataTable MergeTablesByIndex(DataTable t1, DataTable t2){ if (t1 == null || t2 == null) throw new ArgumentNullException("t1 or t2", "Both tables must not be null"); DataTable t3 = t1.Clone(); // first add columns from table1 foreach (DataColumn col in t2.Columns) { string newColumnName = col.ColumnName; int colNum = 1; while (t3.Columns.Contains(newColumnName)) { newColumnName = string.Format("{0}_{1}", col.ColumnName, ++colNum); } t3.Columns.Add(newColumnName, col.DataType); } var mergedRows = t1.AsEnumerable().Zip(t2.AsEnumerable(), (r1, r2) => r1.ItemArray.Concat(r2.ItemArray).ToArray()); foreach (object[] rowFields in mergedRows) t3.Rows.Add(rowFields); return t3;}示例:var dt1 = new DataTable();dt1.Columns.Add("ID", typeof(int));dt1.Columns.Add("Name", typeof(string));dt1.Rows.Add(1, "Jon");var dt2 = new DataTable();dt2.Columns.Add("Country", typeof(string));dt2.Rows.Add("US");var dtMerged = MergeTablesByIndex(dt1, dt2);结果表包含三列ID、Name、Country和一行:1 Jon USThe result table contains three columns ID,Name,Country and a single row: 1 Jon US 这篇关于将 n 个数据表合并为一个数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-06 03:21