Linq with Logic

时间:2012-03-12 09:42:54

标签: linq c#-4.0 entity-framework-4

我有简单的Linq语句(使用EF4)

var efCars = (from d in myentity.Cars
         where d.CarName == inputCar.CarName
         && d.CarIdNumber == inputCar.IdNumber
         && d.Make == inputCar.Make
         select d.Car);

我希望它更聪明,以便它只会查询3个字段中的一个或多个,如果它们有值。

我之前可以做一个测试,然后为inputcar的每个valyes排列都有一个单独的linq语句 (即一个用于所有3个,一个用于如果只有carname有值,一个用于carname和CarIdNumber有值等等)

但必须有一个更聪明的方式

谢谢!

3 个答案:

答案 0 :(得分:1)

如果“没有值”意味着null那么你可以使用空合并运算符??如果填充,则取第一个值,否则取第二个值:

var efCars = (from d in myentity.Cars
where d.CarName == (inputCar.CarName ?? d.CarName
&& d.CarIdNumber == (inputCar.IdNumber && d.CarIdNumber)
&& d.Make == (inputCar.Make && d.Make)  
select d.Car);

这基本上表示如果存在一个值,它必须匹配,否则将其视为匹配

然而,如果你说“当一个特殊值(空字符串)忽略它,否则匹配”然后你可以做两种方法之一(或者可能更多!):

where (inputCar.CarName == "" || d.CarName == inputCar.CarName)  

where (string.IsNullOrEmpty(inputCar.CarName) || d.CarName == inputCar.CarName)

答案 1 :(得分:1)

对于性能(处理数据库查询时),让EF基于过滤器生成查询有时是有益的,而不是使用一个通用查询。当然,您需要分析它是否在这种情况下对您有所帮助(从不过早优化),但这是动态构建查询时的外观:

var efCars =
    from car in myentity.Cars
    select car;

if (inputCar.CarName != null)
{
    efCars =
        from car in efCars
        where care.CarName == inputCar.CarName
        select car;
}

if (inputCar.IdNumber != null)
{
    efCars =
        from car in efCars
        where care.CarIdNumber == inputCar.IdNumber
        select car;
}

if (inputCar.Make != null)
{
    efCars =
        from car in efCars
        where care.Make == inputCar.Make
        select car;
}

答案 2 :(得分:0)

where (inputCar.CarName != null || d.CarName == inputCar.CarName) &&...