The Code is as follows:
Copy codeThe Code is as follows:
/// <Summary>
/// Combine two different able columns into a new DataTable
/// </Summary>
/// <Param name = "dt1"> source table </param>
/// <Param name = "dt2"> tables to be merged </param>
/// <Param name = "primaryKey"> list of required duplicates (empty) </param>
/// <Param name = "maxRows"> maximum number of rows in the merged Table </param>
/// <Returns> merged able </returns>
Public static DataTable MergeDataTable (DataTable dt1, DataTable dt2, string primaryKey, int maxRows)
{
// Determine whether to merge
If (dt1 = null & dt2 = null)
{
Return null;
}
If (dt1 = null & dt2! = Null)
{
Return dt2.Copy ();
}
Else if (dt1! = Null & dt2 = null)
{
Return dt1.Copy ();
}
// Copy the data of dt1
DataTable dt = dt1.Copy ();
// Supplement the dt2 structure (columns not in dt1) to dt
For (int I = 0; I <dt2.Columns. Count; I ++)
{
String cName = dt2.Columns [I]. ColumnName;
If (! Dt. Columns. Contains (cName ))
{
Dt. Columns. Add (new DataColumn (cName ));
}
}
// Copy dt2 data
If (dt2.Rows. Count> 0)
{
Type t = dt2.Rows [0] [primaryKey]. GetType ();
Bool isNeedFilter = string. IsNullOrEmpty (primaryKey )? False: true;
Bool isNeedQuotes = t. Name = "String "? True: false;
Int mergeTableNum = dt. Rows. Count;
For (int I = 0; I <dt2.Rows. Count & mergeTableNum <maxRows; I ++)
{
Bool isNeedAdd = true;
// Determine whether to add the current row if deduplication is required
If (isNeedFilter)
{
String primaryValue = dt2.Rows [I] [primaryKey]. ToString ();
String fileter = primaryKey + "=" + primaryValue;
If (isNeedQuotes)
{
Fileter = primaryKey + "= '" + primaryValue + "'";
}
DataRow [] drs = dt. Select (fileter );
If (drs! = Null & drs. Length> 0)
{
IsNeedAdd = false;
}
}
// Add data
If (isNeedAdd)
{
DataRow dr = dt. NewRow ();
For (int j = 0; j <dt. Columns. Count; j ++)
{
String cName = dt. Columns [j]. ColumnName;
If (dt2.Columns. Contains (cName ))
{
// Prevent the assignment errors due to different types of the same field
If (dt2.Rows [I] [cName]! = Null & dt2.Rows [I] [cName]! = DBNull. Value & dt2.Rows [I] [cName]. ToString ()! = "")
{
Dr [cName] = dt2.Rows [I] [cName];
}
}
}
Dt. Rows. Add (dr );
MergeTableNum ++;
}
}
}
Return dt;
}