Igor Levashov Igor Levashov - 25 days ago 8
C# Question

Multiple using of || and && operands

here is my question, I have 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();

Answer

The easiest way to solve this problem is using brackets:

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


&& has a higher proirity than ||

  • false && false || true -> true

  • false && (false || true) -> false


Sidenote:

there is no need to write x.IsPaid == true since x.IsPaid already is a boolean.

(x.IsPaid || x.IsPaid == null) is the same as (x.IsPaid == true || x.IsPaid == null)

Comments