Guest User

Untitled

a guest
Aug 14th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. inner join with DataTables
  2. string ParentKeyColumn = dt1.Columns[0].ColumnName;
  3. string ChildKeyColumn = dt2.Columns[0].ColumnName;
  4.  
  5. dt2.PrimaryKey = new DataColumn[] { dt2.Columns["Deptno"] };
  6.  
  7. DataRelation drel = new DataRelation("EquiJoin", dt2.Columns["Deptno"], dt1.Columns["Deptno"]);
  8.  
  9. ds.Relations.Add(drel);
  10.  
  11. var result = new DataTable();
  12.  
  13. // Create 1 ID column and the non ID columns
  14. var IDColumn = dataTable1.Columns[0];
  15. result.Columns.Add(IDColumn.ColumnName, IDColumn.DataType);
  16. for (var i = 1; i < dataTable1.Columns.Count; i++)
  17. {
  18. var column = dataTable1.Columns[i];
  19. result.Columns.Add(column.ColumnName, column.DataType);
  20. }
  21.  
  22. for (var i = 1; i < dataTable2.Columns.Count; i++)
  23. {
  24. var column = dataTable2.Columns[i];
  25. result.Columns.Add(column.ColumnName, column.DataType);
  26. }
  27.  
  28. // Create the fields container
  29. var fields = new object[result.Columns.Count];
  30.  
  31. var rows1 = dataTable1.Rows.Cast<DataRow>();
  32. var rows2 = dataTable2.Rows.Cast<DataRow>().ToDictionary(row => (int)row[0]);
  33.  
  34. // Find the rows which ID is common in table 1 and table 2
  35. foreach (var row1 in rows1)
  36. {
  37. int ID = (int)row1[0];
  38. DataRow row2 = null;
  39. if (rows2.TryGetValue(ID, out row2))
  40. {
  41. // Inner join match, add a new row
  42. int fieldIndex = 0;
  43. fields[fieldIndex++] = ID;
  44.  
  45. for (var i = 1; i < dataTable1.Columns.Count; i++)
  46. {
  47. fields[fieldIndex++] = row1[i];
  48. }
  49.  
  50. for (var i = 1; i < dataTable2.Columns.Count; i++)
  51. {
  52. fields[fieldIndex++] = row2[i];
  53. }
  54.  
  55. // Add a new row to the result table using the extracted fields from table 1 and table 2
  56. result.Rows.Add(fields);
  57. }
  58. }
Add Comment
Please, Sign In to add comment