Dawood Awan
Dawood Awan

Reputation: 7328

Join Two DataTables (Some Rows Match some Don't)

I have two Data Tables: T1 and T2

T1 and T2 both have a Column Registration, but T2 doesn't have all the same Rows as T1.

I have to combine the Two Tables such that if the Registration Number is same get columns from T2, if not show Blank, but I need ALL ROWS FROM T1, (IF MATCH OR NOT).

I tried this but I only get matching Rows:

var results = from table1 in T1
              join table2 in T2
              on (String)table1["Registration"] equals (String)table2["Registration"]
              select new
               {
                 Registration = (String)table1["Registration"],
                 DistanceInKM = (decimal)table1["DistanceInKM"],
                 TotalDistanceTravelledKM = (Double)table2["TotalDistanceTravelledKM"]
                };

Upvotes: 1

Views: 747

Answers (1)

Grant Winney
Grant Winney

Reputation: 66449

You're performing an inner join, which only shows rows that exist on both sides.

Try using a left outer join instead:

var results = (from table1 in T1.AsEnumerable()
               join tmp in T2.AsEnumerable() on table1["Registration"] equals tmp["Registration"] into grp
               from table2 in grp.DefaultIfEmpty()
               select new
               {
                   Registration = (String)table1["Registration"],
                   DistanceInKM = (decimal)table1["DistanceInKM"],
                   TotalDistanceTravelledKM = (table2 == null ? (double?)null : (Double)table2["TotalDistanceTravelledKM"])
               };

Upvotes: 1

Related Questions