Michael
Michael

Reputation: 13616

LINQ with conditional where clause

I have this 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);
    }

in LINQ I gave this row:

 where contract.ClientId == clientId

I want this row will be included in where clause only if clientId variable not equal to zero.

Any idea how can I lmake it elegant?

Upvotes: 1

Views: 888

Answers (4)

Nikita Shrivastava
Nikita Shrivastava

Reputation: 3018

you can modify the condition as:

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

Upvotes: 1

Ivan Stoev
Ivan Stoev

Reputation: 205619

For dynamic queries it's better to use the fluent syntax. In this particular case, you can use something like this

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

Upvotes: 2

sujith karivelil
sujith karivelil

Reputation: 29026

Since client id is an external variable you can check it outside the 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);
}

Upvotes: 2

TomDoesCode
TomDoesCode

Reputation: 3681

Just add a check for 0 in the where

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

Upvotes: 7

Related Questions