使用LINQ,C#将两个条件左外连接结构化为一个查询

时间:2017-10-03 10:06:48

标签: c# linq

目前,我正在根据w.Type是1还是2来执行两个查询。如果w.Type为1,我们执行一个连接到Issues表,如果Type是2,我们加入到TSubs表。我正在尝试将这些查询合并为一个。

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();

我正在考虑使用基于此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

到目前为止,我有一些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.....

我正在努力解决的问题是,这不是两个单独连接的左外部。我当前的错误是我在等于之后不能有w.ProductId因为我在这一点上超出了w的范围并且无法弄清楚如何构造linq语句。非常感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

试一试:

chown www-data:www-data /var/www/html/interactor -R

答案 1 :(得分:0)

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 
                };  

请尝试上面的linq。此示例代码未编译或测试。请仅将其用于参考目的。