New Developer
New Developer

Reputation: 3305

Linq query skip querying null coditions

I am very new to linq. I have my clients table. I want to select clients depending on the two conditions

  1. Client type

  2. Client city

So I can write the query like

from c in clients
where c.Type == cType
&& c.City == cCity

Can I use this same query to get the result only providing client type(ignoring the City condition. somithing like *).

What I want to do is if cCity or cType is null ignore the condition.

Is this possible to do?

Upvotes: 0

Views: 837

Answers (3)

Girish Sakhare
Girish Sakhare

Reputation: 763

from c in clients
where (cType == null ? 1 == 1 : c.Type == cType)
&& (cCity == null ? 1 == 1 : c.City == cCity)

Upvotes: 0

Gert Arnold
Gert Arnold

Reputation: 109099

You can compose a LINQ statement before actually executing it:

if (cType != null)
    clients = clients.Where(c => c.Type == cType);
if (cCity != null)
    clients = clients.Where(c => c.City== cCity);
// At this point the query is never executed yet.

Example of how the query can be executed for the first time :

var results = clients.ToList();

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Isn't that what you're looking for?

from c in clients
where (c.Type == null || c.Type == cType)
&& (c.City == null || c.City == cCity)

Upvotes: 1

Related Questions