I have 2 DataTables:
TableA:
id | name | phone
-----------------
1 | Paul | 8523
2 | John | 5217
3 | Stan | 5021
TableB:
id
--
2
5
I want to do a left excluding join between them: I want a DataTable object with all rows of TableA which have a corresponding id Column in TableB.
The result I want to have is this:
id | name | phone
-----------------
1 | Paul | 8523
3 | Stan | 5021
I already have done this with for loops, but I think it could be simpler if I used LINQ. The problem is that all I've tried doesn't work.
How can I do this using LINQ?
The code with for loops is this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim table = LeftExcludingJoin()
If table IsNot Nothing Then
For Each row As DataRow In table.Rows
Console.WriteLine(row.Item("id") & " - " & row.Item("name") & " - " & row.Item("phone"))
Next
End If
End Sub
Private Function LeftExcludingJoin() As DataTable
Dim tableA As New DataTable
tableA.Columns.Add("id")
tableA.Columns.Add("name")
tableA.Columns.Add("phone")
Dim tableB As New DataTable
tableB.Columns.Add("id")
'Rows for tableA
Dim rowA1 As DataRow = tableA.NewRow
rowA1.Item("id") = 1
rowA1.Item("name") = "Paul"
rowA1.Item("phone") = 8523
tableA.Rows.Add(rowA1)
Dim rowA2 As DataRow = tableA.NewRow
rowA2.Item("id") = 2
rowA2.Item("name") = "John"
rowA2.Item("phone") = 5217
tableA.Rows.Add(rowA2)
Dim rowA3 As DataRow = tableA.NewRow
rowA3.Item("id") = 3
rowA3.Item("name") = "Stan"
rowA3.Item("phone") = 5021
tableA.Rows.Add(rowA3)
'Rows for tableB
Dim rowB1 As DataRow = tableB.NewRow
rowB1.Item("id") = 2
tableB.Rows.Add(rowB1)
Dim rowB2 As DataRow = tableB.NewRow
rowB2.Item("id") = 5
tableB.Rows.Add(rowB2)
'Get rows in A which are not in B
Dim tableResult = tableA.Clone
If tableA IsNot Nothing Then
If tableB IsNot Nothing Then
For Each rowA As DataRow In tableA.Rows
Dim coincidence As Boolean = False
For Each rowB As DataRow In tableB.Rows
If rowA.Item("id") = rowB.Item("id") Then
coincidence = True
Exit For
End If
Next
If coincidence = False Then
Dim newResultRow As DataRow = tableResult.NewRow
newResultRow.Item("id") = rowA.Item("id")
newResultRow.Item("name") = rowA.Item("name")
newResultRow.Item("phone") = rowA.Item("phone")
tableResult.Rows.Add(newResultRow)
End If
Next
Else
'All tableA values are part of the result because tableB is Nothing.
Return tableA
End If
Return tableResult
Else
Return Nothing
End If
End Function