在LINQ中的条件上更改连接类型

时间:2017-05-11 13:38:14

标签: c# linq join ternary-operator

例如我有这样的联接:

from cust in customerList 
join prod in productList on cust.ProductId equals prod.Id
join veh in vehicleList on prod.VehicleId equals veh.Id into v
from veh in v.DefaultIfEmpty()
select new {customerName = cust.Name, customerVehicle=veh.VehicleName}

正如您所看到的,在第三和第四行中有一个正确的连接。我想以参数化方式进行此连接。我的意思是如果我有一个变量,我想将连接更改为:

string x ="right";

if(x == right) //execute right join
{
    from cust in customerList 
    join prod in productList on cust.ProductId equals prod.Id
    join veh in vehicleList on prod.VehicleId equals veh.Id into v
    from veh in v.DefaultIfEmpty()
    select new {customerName = cust.Name, customerVehicle=veh.VehicleName}
}
else //execute inner join
{
    from cust in customerList 
    join prod in productList on cust.ProductId equals prod.Id
    join veh in vehicleList on prod.VehicleId equals veh.Id 
    select new {customerName = cust.Name, customerVehicle=veh.VehicleName}
}

我可以使用if语句执行此操作,但我认为代码太多且重复次数过多。那么我可以在join行内使用三元运算符来应用这个条件吗?提前谢谢。

编辑:

正如我所说,我可以使用question中建议的if语句来执行此操作。但我的原始代码包含13个嵌套连接。因此,为每种可能性编写ifs会导致非常难看的代码。你可以帮帮我吗?

2 个答案:

答案 0 :(得分:1)

我认为您可以做的最好的事情是在变量中设置查询的公共基础部分,然后根据您的条件添加查询的其余部分。

string x ="right";
var qbase = from cust in customerList 
            join prod in productList on cust.ProductId equals prod.Id;

if(x == "right") { //execute right join
    qbase = from custprod in qbase
            join veh in vehicleList on prod.VehicleId equals veh.Id into v
            from veh in v.DefaultIfEmpty()
            select new {customerName = custprod.Name, customerVehicle=veh.VehicleName};
}
else { //execute inner join
    qbase = from custprod in qbase
            join veh in vehicleList on prod.VehicleId equals veh.Id 
            select new {customerName = custprod.Name, customerVehicle=veh.VehicleName};
}

答案 1 :(得分:1)

尝试代码

string x ="right";

var result= (from cust in customerList 
join prod in productList on cust.ProductId equals prod.Id
join veh in vehicleList on prod.VehicleId equals veh.Id into v
from veh in v.DefaultIfEmpty()
select new {customerName = cust.Name,customerVehicle=veh.VehicleName}).ToList();

if(x=="right")
result=result.Where(c=>c.customerVehicle!=null).ToList();

X == right然后Null值Is删除结果否则结果默认左连接