[英]Using LINQ to JOIN two datatables using two key columns
數據表A:
Key1 | Key2 | A | 乙
[1 1 ...]
[1 2 ...]
數據表B:
Key1 | Key2 | x | ÿ
[1 1 ...]
[1 2 ...]
所需結果:
Key1 | Key2 | A | B | X | ÿ
[1 1 ...]
[1 2 ...]
在最終結果中,列A,B,X和Y已添加到新數據表中。 發生這種情況是因為在數據表A和B中key1和key2相等。給定條件-(Key1和Key2是等價的),是否可以使用完全外部聯接?
試試這個代碼的朋友:
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();
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();
假設Key1和Key2為int
類型,而AB,X和Y為string
類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.