2

i have 3 tables

t1==>

 t1.ID    t1.co1     t1.col2

 1       a         b              
 2       a         b   

t2==>

 t2.ID    t2.co1     t2.col2

  1       a         b              
  2       a         b     

t3==>

 t3.ID    t3.co1     t3.col2

 1       a         b              
 2       a         b         

i want inner join between all three tables using Linq and want selected column in 4th datatable.

equivalent sql query:

SELECT t1.ID,t2.col1,t3.col2 
  FROM t1
INNER JOIN t2 ON t1.ID=t2.ID
INNER JOIN t3 ON t1.ID=t3.ID

t4==>

 t1.ID    t2.co1     t3.col2

 1        a         b              
 2        a         b  
0

2 Answers 2

3

Something like this

var Result = 
    from row1 in t1
    join row2 in t2 on row1.ID equals row2.ID
    join row3 in t3 on row1.ID equals row3.ID
    select new { ID = row1.ID, Col1 = row2.col1, Col2 = row3.col2 }

DataTable dt = Result.CopyToDataTable();
4
  • haste makes waste)) Thanks
    – Alex
    Feb 22, 2013 at 10:40
  • @voo: thanks for ur reply :). i did almost same but how can i convert var Result to datatable? Feb 22, 2013 at 10:47
  • 1
    @WebDevelopmentHurricane, check my answer, you need to use CopyToDataTable() method.
    – Kaf
    Feb 22, 2013 at 10:50
  • ...but honestly, you don't want to use a DataTable. Like, ever :-). Feb 22, 2013 at 11:01
1

Use LoadDataRow() to get a DataTable from an anonymous type as here. Else Result.CopyToDataTable().

//Get the column list as same as table1 to new datatable
DataTable table4 = table1.Clone();

var Result = 
  from x in t1.AsEnumerable() join 
       y in t2.AsEnumerable() on x.Field<int>("ID") equals y.Field<int>("ID") join 
       z in t3.AsEnumerable() on x.Field<int>("ID") equals z.Field<int>("ID")
  select new table4.LoadDataRow( 
       new object[] { 
              x.ID, 
              y.col1, 
              z.col2 
           }, false);
1
  • it doesn't work for selecting "Selected Columns". select x).CopyToDataTable(); it works fine but when new { ID = x.ID, col1 = y.col1, col2 = z.col2 }.CopyToDataTable(); -- it doesn't Feb 22, 2013 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.