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();
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With