简体   繁体   中英

Join two datatables with Linq

I am trying to join two datatables which I have nearly done after searching the web for examples.

The problem I have is it only shows the rows where there is a match; how do I show all of the rows in t1 and then if there is a match show something in a column to say there is a match?

Below is the code I am using:

Dim Query = From t1 In dt.AsEnumerable() Join t2 In dt2.AsEnumerable()
        On t1.Field(Of String)("Surname") Equals t2.Field(Of String)("VisitorFob")
            Select New With {.Surname = t1.Field(Of String)("Surname"), .VisitorFob = t2.Field(Of String)("VisitorFob")}

Dim newTable As New DataTable()

newTable.Columns.Add("Surname", GetType(String))
newTable.Columns.Add("VisitorFob", GetType(String))

For Each rowInfo In Query
    newTable.Rows.Add(rowInfo.Surname, rowInfo.VisitorFob)
Next

You could use a left outer join like with this question to include data from the first table regardless of matches.

LEFT OUTER JOIN gets all records from the first table, no matter if there is a match on the second table. If there is a match, it gets the values of the second table, if there is not a match then it returns NULL. article explaing some of the linq query methods

I haven't tested this but I think this would work for your query if your current query works:

   Dim Query = From t1 In dt.AsEnumerable() 
      Group Join t2 In dt2.AsEnumerable()
      On t1.Field(Of String)("Surname") Equals t2.Field(Of String)("VisitorFob")
      Into temp = Group
      From b In temp.DefaultIfEmpty()   
      Select New With {.Surname = t1.Field(Of String)("Surname"),
       .VisitorFob = If(b Is Nothing, String.Empty, b.Field(Of String)("VisitorFob"))}

    Dim newTable As New DataTable()

    newTable.Columns.Add("Surname", GetType(String))
    newTable.Columns.Add("VisitorFob", GetType(String))

    For Each rowInfo In Query
        newTable.Rows.Add(rowInfo.Surname, rowInfo.VisitorFob)
    Next

Your "VisitorFob" value returned from t2 would be null to indicate that there was no match to t1 as well since the left outer join would return the t1 values without the matching t2 values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM