将两张DataTable进行join
Posted 爽朗的刘备
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将两张DataTable进行join相关的知识,希望对你有一定的参考价值。
方法一:在数据库中若是两张表中共同字段一个非空一个为NULL,可以通过sql语句进行合并:
coalesce(t1.region_code,t2.region_code) as REGIONID
方法二:粗略写了个算法,也没有进行算法优化,仅供参考。
/// <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; }
以上是关于将两张DataTable进行join的主要内容,如果未能解决你的问题,请参考以下文章