我有3张桌子
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
我希望使用Linq在所有三个表之间进行内部连接,并希望在第4个数据表中选择列。
等效的sql查询:
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 :(得分:3)
像这样的东西
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();
答案 1 :(得分:1)
使用LoadDataRow()
将 anonymous
类型的DataTable作为here。其他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);