Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple using of || and && operands

I have a query using Entity Framework. It has many different operands and I am confused with its priority. I am getting the wrong result. I need all records that IsPaid == true or IsPaid == null, also all records must be TypeId == 1 or TypeId == 2, also must be CityId == 1 and CategoryId == 2. For some reason it doesn't evaluate CityId and CategoryId. What am I doing wrong? Thanks.

var list = db.Ads.Where (x =>
               x.IsPaid == true || x.IsPaid == null &&
               x.TypeId == 1 || x.TypeId == 2 &&
               x.CityId == 1 && x.CategoryId == 2
).ToList();
like image 239
Igor Levashov Avatar asked Nov 09 '16 07:11

Igor Levashov


1 Answers

The best way to solve this problem is using brackets. You should always use them even if you know the binding prioritys, to increase readability of your code.

(x.IsPaid == true || x.IsPaid == null) && (x.TypeId == 1 || x.TypeId == 2) && x.CityId == 1 && x.CategoryId == 2


&& has a higher proirity than ||

So false && false || true would be translated to (false && false) || true => true


Sidenote as mentioned by @Joey:

Instead of (x.IsPaid == true || x.IsPaid == null) you can write (x.IsPaid != false).

like image 69
Tim Schmidt Avatar answered Oct 27 '22 18:10

Tim Schmidt