Compare datatables
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<span style="font-size: 10pt;"> [code lang="vb"]#Region "Compare two DataTables and return a DataTable with DifferentRecords" ''' <summary> ''' Compare two DataTables and return a DataTable with DifferentRecords ''' </summary> ''' <param name="FirstDataTable">FirstDataTable</param> ''' <param name="SecondDataTable">SecondDataTable</param> ''' <returns>DifferentRecords</returns> Public Function getDifferentRecords(FirstDataTable As DataTable, SecondDataTable As DataTable) As DataTable 'Create Empty Table Dim ResultDataTable As New DataTable("ResultDataTable") 'use a Dataset to make use of a DataRelation object Using ds As New DataSet() 'Add tables ds.Tables.AddRange(New DataTable() {FirstDataTable.Copy(), SecondDataTable.Copy()}) 'Get Columns for DataRelation Dim firstColumns As DataColumn() = New DataColumn(ds.Tables(0).Columns.Count - 1) {} For i As Integer = 0 To firstColumns.Length - 1 firstColumns(i) = ds.Tables(0).Columns(i) Next Dim secondColumns As DataColumn() = New DataColumn(ds.Tables(1).Columns.Count - 1) {} For i As Integer = 0 To secondColumns.Length - 1 secondColumns(i) = ds.Tables(1).Columns(i) Next 'Create DataRelation Dim r1 As New DataRelation(String.Empty, firstColumns, secondColumns, False) ds.Relations.Add(r1) Dim r2 As New DataRelation(String.Empty, secondColumns, firstColumns, False) ds.Relations.Add(r2) 'Create columns for return table For i As Integer = 0 To FirstDataTable.Columns.Count - 1 ResultDataTable.Columns.Add(FirstDataTable.Columns(i).ColumnName, FirstDataTable.Columns(i).DataType) Next 'If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable. ResultDataTable.BeginLoadData() For Each parentrow As DataRow In ds.Tables(0).Rows Dim childrows As DataRow() = parentrow.GetChildRows(r1) If childrows Is Nothing OrElse childrows.Length = 0 Then ResultDataTable.LoadDataRow(parentrow.ItemArray, True) End If Next 'If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable. For Each parentrow As DataRow In ds.Tables(1).Rows Dim childrows As DataRow() = parentrow.GetChildRows(r2) If childrows Is Nothing OrElse childrows.Length = 0 Then ResultDataTable.LoadDataRow(parentrow.ItemArray, True) End If Next ResultDataTable.EndLoadData() End Using Return ResultDataTable End Function #End Region[/code] </span> |