[英]Structuring two conditional left outer joins into one query using LINQ, C#
Currently, I am executing two queries based upon whether w.Type
is either 1 or 2. If w.Type
is 1 we perform a join to the Issues table and if the Type is 2 we join to the TSubs table. 当前,我正在基于
w.Type
是1还是2执行两个查询。如果w.Type
为1,则执行对Issues表的联接,如果Type。为2,则对TSubs表联接。 I am trying to merge these queries into one. 我正在尝试将这些查询合并为一个。
var productIdOne = (from w in listAbandonedCarts
join i in Issues on w.ProductId equals i.Id
where w.Type == 1
select new { i.Title.Name }).ToList();
var productIdTwo = (from w in listAbandonedCarts
join ts in TSubs on w.ProductId equals ts.Id
where w.Type == 2
select new { ts.Title.Name }).ToList();
I am considering using two left outer joins based upon this SQL psuedo-code 我正在考虑基于此SQL伪代码使用两个左外部联接
SELECT*
FROM P_carts pc
LEFT OUTER tSubs ts on ts.id = pc.productid and pc.Type = 2
LEFT OUTER issues i on i.id = pc.productid and pc.Type = 1
So far i have some linq pseudo coded but i'm struggling to get the syntax correct for the two conditional joins 到目前为止,我有一些linq伪编码,但是我正在努力使两个条件连接的语法正确
var listProducts = (from w in listAbandonedCarts
join i in Issues on w.ProductId equals i.Id into iN && w.ProductId == 1
from i in iN.DefaultIfEmpty()
join into ts in TSubs.....
The problem I'm struggling with is that this isn't a double left outer its two separate joins. 我苦苦挣扎的问题是,这不是它的两个单独连接的左外角。 My current error is that i cannot have
w.ProductId
after the equals because I'm out of scope of w at this point and can't figure out how to structure the linq statement. 我当前的错误是,在
w.ProductId
之后我无法拥有w.ProductId
,因为此时我不在w的范围内,并且无法弄清楚如何构造linq语句。 Any help would be much appreciated, thanks! 任何帮助将不胜感激,谢谢!
Give this a shot: 试一下:
var productIds = (
from w in listAbandonedCarts
from i in Issues.Where(issue => issue.Id == w.ProductId && w.Type == 1).DefaultIfEmpty()
from t in TSubs.Where(tsub => tsub.Id == w.ProductId && w.Type == 2).DefaultIfEmpty()
select new {Name = (w.Type == 1 ? i.Title.Name : t.Title.Name)})
.ToList();
var listProducts = (from w in listAbandonedCarts
join i in Issues on w.ProductId equals i.Id && w.ProductId == 1 into iN
from i in iN.DefaultIfEmpty()
join into ts in TSubs on ts.id equals pc.productid into tsBag
from ts in tsBag.DefaultIfEmpty()
select new
{
// All columns you need
};
Please try the above linq. 请尝试上面的linq。 This sample code is not compiled nor tested.
此示例代码未经编译或测试。 Please use this for reference purpose only.
请仅将此用作参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.