0

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?

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I want if cType==null skip querying that condition
when c.Type is null the whole result of (c.Type == null || c.Type == cType) is True, Therefore it is replaced by True so it skips that and checks next condition chain.. and so on
0

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();

Comments

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

4 Comments

Can you explain what is benefit of hardcoding true value as 1 == 1? And benefit of ternary operation when it returns boolean value VS simple OR condition
It something similar to @Gert answer. 1 == 1 is always true i.e. we are skipping the condition if cType or cCity is null.
I know that 1 == 1 is always true. Why not to write true instead: cType == null ? true : c.Type == cType? If cType is null, then we return true else we return c.Type == cType. But that is how OR works: cType == null || c.Type == cType. So, questions are still here.
oh I misunderstood the question. Yup you are right we can have true there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.