There are many articles on how to merge DataTable on the Internet. Based on the common requirements in project development and the practices on the internet, I wrote a general method for merging DataTable, the main function is to merge two datatables (the structure can be different, for example, the fields are not completely consistent), and refresh the data based on a column value.
There are many articles on how to merge DataTable on the Internet. Based on the common requirements in project development and the practices on the internet, I wrote a general method for merging DataTable, the main function is to merge two datatables (the structure can be different, for example, the fields are not completely consistent), and refresh the data based on a column value.
The Code is as follows:
The Code is as follows:
///
/// Combine two different able columns into a new DataTable
///
/// Source table
/// Tables to be merged
/// List of required duplicates (empty, no duplicates)
/// Maximum number of rows in the merged Table
/// Merged able
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;
}