Iason
Iason

Reputation: 249

Using LINQ to JOIN two datatables using two key columns

Datatable A:

Key1 | Key2 | A | B

[ 1 1 ... ]

[ 1 2 ... ]

Datatable B:

Key1 | Key2 | x | Y

[ 1 1 ... ]

[ 1 2 ... ]

Desired result:

Key1 | Key2 | A | B | X | Y

[ 1 1 ... ]

[ 1 2 ... ]

In the end result columns A, B, X and Y have been added to the new datatable. This happened because key1 and key2 were equal in both datatable A and B. Would this be possible to do with a full outer join, given a condition - (Key1 and Key2 are euqal) ?

Upvotes: 1

Views: 4173

Answers (2)

Shyju
Shyju

Reputation: 218942

var list1 = (from t1 in dataTable1.AsEnumerable()
                select new
                {
                    Key1 = t1.Field<int>("Key1"),
                    Key2 = t1.Field<int>("Key2"),
                    A = t1.Field<string>("A"),
                    B = t1.Field<string>("B")
                });

var list2 = (from b in dataTable2.AsEnumerable()
                select new
                {
                    Key1 = b.Field<int>("Key1"),
                    Key2 = b.Field<int>("Key2"),
                    X = b.Field<string>("X"),
                    Y = b.Field<string>("Y")
                });

// Now join the 2 collections and get the result you want.

var result = (from x in list1
                join y in list2 on new { x.Key1,x.Key2} equals new { y.Key1,y.Key2 }
                select new { A = x.A, X = y.X }).ToList();

Assuming Key1 and Key2 are int type and A.B,X and Y are of string type.

Upvotes: 1

Beldi Anouar
Beldi Anouar

Reputation: 2180

Try this code friend :

var req = (from A in DatatableA
       join B in DatatableB 
        on A.Key1
            equals B.Key1  into DatatableResult
            select new
           {
                  Key1 = A.Key1    ,
                 Key2 = A.Key2    ,
               A= A.A ,
               x= B.x ,
               y= B.y ,

             }).ToList();

Upvotes: 1

Related Questions