Common method for merging datatable onlineArticleMany of them, combined with common requirements in project development and the practices on the internet, write a common method for merging datatable, the main function is to merge two datatable (the structure can be different, if the fields are not completely consistent), and you can perform deduplication based on a column value.CodeAs follows:
View code
/// <Summary>
/// Merges 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, no duplicates) </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 dt1 data
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 ;
// If you want to remove duplicates, determine whether to add the current row.
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 & Amp; Drs. Length & gt; 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 ))
{
// Prevents assignment errors due to different types of values in 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;
}