我很难将SQL转换为LINQ语句。
这是SQL语句:
SELECT * FROM dataTableA INNER JOIN dataTableB ON dataTableA.ID =dataTableB.SNo OR
dataTableA.Address = dataTableB.Address
WHERE (dataTableA.Name = dataTableB.UserName)
OR
部分On
部分我不知道如何编写LINQ语法。我在没有OR
条件的情况下试过了以下报价。请建议。
var matches = from rowA in dataTableA.AsEnumerable()
join rowB in dataTableB.AsEnumerable()
on rowA["ID"].ToString().Trim() equals rowB["SNo"].ToString().Trim()
where rowA["Name"].ToString().Trim() == rowB["UserName"].ToString().Trim()
select new { rowA, rowB } ;
答案 0 :(得分:1)
试试这种方式
var matches = from rowA in dataTableA.AsEnumerable()
from rowB in dataTableB.AsEnumerable().Where(x=>x.SNo==rowA.ID || x.Address ==rowA.Address) .AsEnumerable()
where rowA["Name"].ToString().Trim() == rowB["UserName"].ToString().Trim()
select new { rowA, rowB } ;
答案 1 :(得分:1)
您可以使用复合键加入ID
和 Adress
https://msdn.microsoft.com/en-us/library/bb907099.aspx
dataTableA.AsEnumerable().join(dataTableB.AsEnumerable(),
ta => new {ta.ID, ta.Adress}, tb => new {tb.SNo, tb.Adress},
(ta, tb) => new {ta, tb})
如果您想加入ID
或 Adress
,您可以联合2个联接,我认为仍然应该比n快where
s:Why is LINQ JOIN so much faster than linking with WHERE?
dataTableA.AsEnumerable().join(dataTableB.AsEnumerable(),
ta => ta.ID, tb => tb.SNo, (ta, tb) => new {ta, tb})
.union(dataTableA.AsEnumerable().join(dataTableB.AsEnumerable(),
ta => ta.Adress, tb => tb.Adress, (ta, tb) => new {ta, tb}))
答案 2 :(得分:0)
var matches = dataTableA.AsEnumerable()
.Select(a => new {
RowA = a,
RowB = dataTableB.AsEnumerable().FirstOrDefault(b => ((b["SNo"] == a["ID"]) || (b["Address"].Equals(a["Address"]))))
})
.Where(pair => pair.RowB != null) //to replicate the inner-join
.Where(pair => pair.RowA["Name"].Equals(pair.RowB["Username"]));
答案 3 :(得分:0)
在对Mukesh Kalgude的回答进行微小修改后,问题解决了。下面是最终的工作代码。感谢所有人的善意建议。
var matches = from rowA in dataTableA.AsEnumerable()
from rowB in dataTableB.AsEnumerable().Where(x=>x["SNo"]==rowA["ID"] || x["Address"]==rowA["Address"]) .AsEnumerable()
where rowA["Name"].ToString().Trim() == rowB["UserName"].ToString().Trim()
select new { rowA, rowB } ;