标签:ret datarow 优化 行合并 ble ++ ram style 拷贝
/// <param name="dt1">要合并的表一</param> /// <param name="dt2">要合并的表二</param> /// <param name="KeyColName">dt1与dt2联系的关键列名 </param> public DataTable MergeDataTable(DataTable dt1, DataTable dt2, String KeyColName) { //定义临时变量 DataTable dtReturn = new DataTable(); int i = 0; int j = 0; int k = 0; int l=0; int colKey1 = 0; int colKey2 = 0; //设定表dtReturn的名字 dtReturn.TableName = dt1.TableName; //设定表dtReturn的列名 for (i = 0; i < dt1.Columns.Count; i++) { if (dt1.Columns[i].ColumnName == KeyColName) { colKey1 = i; } dtReturn.Columns.Add(dt1.Columns[i].ColumnName); } for (j = 0; j < dt2.Columns.Count; j++) { if (dt2.Columns[j].ColumnName == KeyColName) { colKey2 = j; continue; } dtReturn.Columns.Add(dt2.Columns[j].ColumnName); } //建立表的空间 //int len = dt1.Rows.Count + dt2.Rows.Count; int len = dt1.Rows.Count; for (i = 0; i < dt2.Rows.Count; i++) { int v = -1; for (j = 0; j < dt1.Rows.Count; j++) { string z = dt2.Rows[i][colKey1].ToString(); string x = dt1.Rows[j][colKey2].ToString(); if (dt2.Rows[i][colKey1].ToString() == dt1.Rows[j][colKey2].ToString()) { v = 1; break; } } if (v == -1) { len++; } } for (i = 0; i < len; i++) { DataRow dr; dr = dtReturn.NewRow(); dtReturn.Rows.Add(dr); } for (i = 0; i < dt1.Rows.Count; i++) { //表dt1的第i行数据拷贝到dtReturn中去 for (j = 0; j < dt1.Columns.Count; j++) { dtReturn.Rows[i][j] = dt1.Rows[i][j].ToString(); } } int m = -1; int n=dt1.Rows.Count; //查找的dt2中KeyColName的数据,与dt1相同的行 for (l = 0; l < dt2.Rows.Count; l++) { for (k = 0; k < dt1.Rows.Count; k++) { string z = dt2.Rows[l][colKey1].ToString(); string x = dt1.Rows[k][colKey2].ToString(); if (dt2.Rows[l][colKey1].ToString() == dt1.Rows[k][colKey2].ToString()) { m = k; break; } else { m = -1; } } //表dt2的第m行数据拷贝到dtReturn中去,且不要KeyColName(ID)列 if (m != -1) { string p = dt2.Rows[l][0].ToString(); dtReturn.Rows[m][2] = dt2.Rows[l][1].ToString(); } else { dtReturn.Rows[n][0]=dt2.Rows[l][0].ToString(); dtReturn.Rows[n][2] = dt2.Rows[l][1].ToString(); n++; } } return dtReturn; }
标签:ret datarow 优化 行合并 ble ++ ram style 拷贝
原文地址:http://www.cnblogs.com/shuanglangdeliubei/p/7475458.html