我有2个DataTable。我想使用LINQ在差异列上加入2个数据表。怎么做?
表A:
+--------+-------+-------+
| ACol1 | ACol2 | ACol3 |
+--------+-------+-------+
| 1 | tbA12 | tbA13 |
| 2 | tbA22 | tbA23 |
| 3 | tbA32 | tbA33 |
| 4 | tbA42 | tbA43 |
| 5 | tbA52 | tbA53 |
+--------+-------+-------+
表B:
+-------+-------+-------+
| BCol1 | BCol2 | BCol3 |
+-------+-------+-------+
| 1 | XX | tbB13 |
| XX | 1 | tbB23 |
| XX | 2 | tbB33 |
| 4 | XX | tbB43 |
+-------+-------+-------+
SELECT a.*, b.BCol3
FROM tableA a
JOIN tableB b ON a.ACol1=b.BCol1 OR a.ACol1=b.BCol2
+--------+-------+-------+-------+
| ACol1 | ACol2 | ACol3 | BCol3 |
+--------+-------+-------+-------+
| 1 | tbA12 | tbA13 | tbB13 |
| 1 | tbA12 | tbA13 | tbB23 |
| 2 | tbA22 | tbA23 | tbB33 |
| 4 | tbA42 | tbA43 | tbB43 |
+--------+-------+-------+-------+
目前我的LINQ查询如下:
var query1= from rowA in tableA.AsEnumerable()
join rowB in tableB.AsEnumerable()
on rowA["ACol1"].ToString() equals rowB["BCol1"].ToString()
select new
{
rowA["ACol1"],
rowA["ACol2"],
rowA["ACol3"],
rowB["BCol3"]
};
var query2= from rowA in tableA.AsEnumerable()
join rowB in tableB.AsEnumerable()
on rowA["ACol1"].ToString() equals rowB["BCol2"].ToString()
{
rowA["ACol1"],
rowA["ACol2"],
rowA["ACol3"],
rowB["BCol3"]
};
var result=query1.Union(query2);
更好的想法如何解决这个问题?
答案 0 :(得分:1)
LINQ对具有非平凡条件的JOIN的支持非常有限。您可以进行交叉连接+将条件移动到where子句。
var query1= from rowA in tableA.AsEnumerable()
from rowB in tableB.AsEnumerable()
where rowA["ACol1"].ToString() == rowB["BCol1"].ToString()
|| rowA["ACol1"].ToString() == rowB["BCol2"].ToString()
select new
{
rowA["ACol1"],
rowA["ACol2"],
rowA["ACol3"],
rowB["BCol3"]
};
答案 1 :(得分:1)
试试这个: -
var result = from a in tableA.AsEnumerable()
from b in tableB.AsEnumerable()
where a.Field<string>("ACol1") == b.Field<string>("BCol1")
|| a.Field<string>("ACol1") == b.Field<string>("BCol2")
select new
{
a["ACol1"],
a["ACol2"],
a["ACol3"],
b["BCol3"]
};
以下是完整的工作Fiddle,您可以在编辑器中复制粘贴并进行测试,因为它不支持DotNetFiddle中的AsEnumerable
。