LINQ with conditional where子句

时间:2015-10-07 08:43:32

标签: c# linq

我有这个LINQ:

    private static IQueryable<Contract> getValidContracts(DbContext context, DateTime date,int clientId)
    {
        return (from contract in context.Set<Contract>()
                where contract.ValidityDate >= date
                where contract.ClientId == clientId
                select contract);
    }
LINQ中的

我给了这一行:

 where contract.ClientId == clientId

我希望只有当 clientId 变量不等于零时,此行才会包含在where子句中。

任何想法我怎样才能使它优雅?

4 个答案:

答案 0 :(得分:7)

只需在其中添加0的检查

where ((contract.ClientId == clientId && clientId != 0) || clientId == 0)

答案 1 :(得分:2)

由于客户端ID是外部变量,您可以在LINQ外部检查它:

if(clientId==0)
{
   return (from contract in context.Set<Contract>()
                where contract.ValidityDate >= date
                select contract);
}
else
{
 return (from contract in context.Set<Contract>()
                where contract.ValidityDate >= date
                where contract.ClientId == clientId
                select contract);
}

答案 2 :(得分:2)

对于动态查询,最好使用流畅的语法。在这种特殊情况下,您可以使用类似这样的内容

private static IQueryable<Contract> getValidContracts(DbContext context, DateTime date, int clientId)
{
    var query = context.Set<Contract>().Where(contract => contract.ValidityDate >= date);
    if (clientId != 0)
        query = query.Where(contract => contract.ClientId == clientId);
    return query; 
}

答案 3 :(得分:1)

您可以将条件修改为:

where ((clientId!=0)?(contract.ClientId == clientId):true)