-1

Does the multiple .Where() act as an AND (&&) or act as Or (||) for example:

 var db = new myContext();
 var query = db.User.Where(u => u.Gender == "Male");
 query = query.Where(u => u.IsActive == true);

Is it equivalent to :

   Select *
   from user
   where gender = 'Male' 
     and IsActive = true;
s.alhaj
  • 141
  • 2
  • 11

2 Answers2

2

You are passing the result of one filter through another, so logically they will act like an "and".

Say you have a deck of cards. You then use a "filter" that only gives you red cards. You then want to pass the result to another filter that only gives you sevens.

So effectively you get cards that are red AND have a value of seven.

Is there a way to change this behavior and make it act as 'or'?

No, there's not a way to take a query that has a Where clause and "append" a second Where clause that acts like an or.

If you're trying to dynamically append filters with an "or" operation, the most direct way is to combine the two predicates with an "or" (see "Or" equivalent in Linq Where() lambda expression)

One other way would be to re-use the original query, use two separate Where queries, and Union the results.

var result1 = a.Where(u => u.Gender == "Male");
var result2 = a.Where(u => u.IsActive == true);

var result = result1.Union(result2);

But there may be performance concerns with this sort of "indirect" OR clause

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • Is there a way to change this behavior and make it act as 'or'. The purpose of this is to use a query builder or dynamic query? @D Stanley – s.alhaj Apr 08 '20 at 12:45
0

Just use && operator:

var query = db.User.Where(u => u.Gender == "Male" && u.IsActive == true);

The && operator means and. That the above condition can be read like get all users with gender=="Male" and isActive=="true"

StepUp
  • 36,391
  • 15
  • 88
  • 148