In the following example, 3 Join methods are implemented to connect two DataTable, equivalent to the SQL inner join method, and return all columns of the DataTable.
If the DataColumn in the two DataTable is duplicated, the second is set to Columnname+ "_second", and the following code is in the hope of helping.
Using System;
Using System.Data;
Namespace WindowsApplication1
{
public class Sqlops
{
Public Sqlops ()
{
}
public static DataTable Join (DataTable A, DataTable Second, datacolumn[] FJC, datacolumn[] SJC)
{
Create a new DataTable
DataTable table = new DataTable ("Join");
Use a DataSet to leverage DataRelation
Using (DataSet ds = new DataSet ())
{
Copy the DataTable into the dataset
Ds. Tables.addrange (New Datatable[]{first.copy (), Second.copy ()});
datacolumn[] Parentcolumns = new DATACOLUMN[FJC. Length];
for (int i = 0; i < Parentcolumns. Length; i++)
{
Parentcolumns[i] = ds. Tables[0]. Columns[fjc[i]. ColumnName];
}
datacolumn[] Childcolumns = new DATACOLUMN[SJC. Length];
for (int i = 0; i < Childcolumns. Length; i++)
{
Childcolumns[i] = ds. TABLES[1]. Columns[sjc[i]. ColumnName];
}
Create Association
DataRelation r = new DataRelation (string. Empty,parentcolumns,childcolumns,false);
Ds. Relations.Add (R);
Create a column for the associated table
for (int i = 0; i < First.Columns.Count; i++)
{
Table. Columns.Add (First.columns[i]. ColumnName, First.columns[i]. DataType);
}
for (int i = 0; i < Second.Columns.Count; i++)
{
See if there are any duplicate columns, if there is a column in the second DataTable added _second
if (!table. Columns.contains (Second.columns[i]. ColumnName))
Table. Columns.Add (Second.columns[i]. ColumnName, Second.columns[i]. DataType);
Else
Table. Columns.Add (Second.columns[i]. ColumnName + "_second", Second.columns[i]. DataType);
}
Table. Beginloaddata ();
foreach (DataRow firstrow in DS. Tables[0]. Rows)
{
Get the data for the row
datarow[] Childrows = firstrow. GetChildRows (R);
if (childrows!= null && childrows. Length > 0)
{
object[] Parentarray = firstrow. ItemArray;
foreach (DataRow secondrow in Childrows)
{
object[] Secondarray = Secondrow. ItemArray;
object[] Joinarray = new Object[parentarray. Length+secondarray. Length];
Array.copy (Parentarray,0,joinarray,0,parentarray. Length);
Array.copy (Secondarray,0,joinarray,parentarray. Length,secondarray. Length);
Table. Loaddatarow (joinarray,true);
}
}
}
Table. Endloaddata ();
}
return table;
}
public static DataTable Join (DataTable A, DataTable Second, DataColumn FJC, DataColumn SJC)
{
Return Join (Second, New DATACOLUMN[]{FJC}, New DATACOLUMN[]{SJC});
}
public static DataTable Join (DataTable A, DataTable Second, String FJC, String SJC)
{
Return Join (Second, New DATACOLUMN[]{FIRST.COLUMNS[FJC]}, new DATACOLUMN[]{FIRST.COLUMNS[SJC]};
}
}
}