Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- inner join with DataTables
- string ParentKeyColumn = dt1.Columns[0].ColumnName;
- string ChildKeyColumn = dt2.Columns[0].ColumnName;
- dt2.PrimaryKey = new DataColumn[] { dt2.Columns["Deptno"] };
- DataRelation drel = new DataRelation("EquiJoin", dt2.Columns["Deptno"], dt1.Columns["Deptno"]);
- ds.Relations.Add(drel);
- var result = new DataTable();
- // Create 1 ID column and the non ID columns
- var IDColumn = dataTable1.Columns[0];
- result.Columns.Add(IDColumn.ColumnName, IDColumn.DataType);
- for (var i = 1; i < dataTable1.Columns.Count; i++)
- {
- var column = dataTable1.Columns[i];
- result.Columns.Add(column.ColumnName, column.DataType);
- }
- for (var i = 1; i < dataTable2.Columns.Count; i++)
- {
- var column = dataTable2.Columns[i];
- result.Columns.Add(column.ColumnName, column.DataType);
- }
- // Create the fields container
- var fields = new object[result.Columns.Count];
- var rows1 = dataTable1.Rows.Cast<DataRow>();
- var rows2 = dataTable2.Rows.Cast<DataRow>().ToDictionary(row => (int)row[0]);
- // Find the rows which ID is common in table 1 and table 2
- foreach (var row1 in rows1)
- {
- int ID = (int)row1[0];
- DataRow row2 = null;
- if (rows2.TryGetValue(ID, out row2))
- {
- // Inner join match, add a new row
- int fieldIndex = 0;
- fields[fieldIndex++] = ID;
- for (var i = 1; i < dataTable1.Columns.Count; i++)
- {
- fields[fieldIndex++] = row1[i];
- }
- for (var i = 1; i < dataTable2.Columns.Count; i++)
- {
- fields[fieldIndex++] = row2[i];
- }
- // Add a new row to the result table using the extracted fields from table 1 and table 2
- result.Rows.Add(fields);
- }
- }
Add Comment
Please, Sign In to add comment