I have a predicate builder that initially evaluates to false
. Because of this, the very next expression should be a logical Or
. But if I need a logical And
I need to keep track of a boolean value. And this boolean value hasPassedFirstCheck
is the thing I want to get rid of.
var cars = PredicateBuilder.False<Cars>();
var hasPassedFirstCheck = false;
if (filterObject.CarTypes.Contains(CarTypes.Truck))
{
if (sf.ServiceTypes.Count < 2 && !hasPassedFirstCheck)
cars = cars.And(x => x.CarType== CarType.DJ);
else
cars = hasPassedFirstCheck
? cars.Or(x => x.CarType== CarType.DJ)
: cars.And(x => x.CarType== CarType.DJ);
hasPassedFirstCheck = true;
}
if (filterObject.CarTypes.Contains(CarTypes.SUV))
{
if (condition && !hasPassedFirstCheck)
cars = cars.And(x => x.CarType == CarType.SUV);
else
cars = hasPassedFirstCheck
? cars.Or(x => x.CarType == CarType.SUV)
: cars.And(x => x.CarType == CarType.SUV);
hasPassedFirstCheck = true;
}
if (filterObject.CarTypes.Contains(CarTypes.Limo))
{
if (condition && !hasPassedFirstCheck)
cars = cars .And(x => x.CarType == CarType.Limo);
else
cars = hasPassedFirstCheck
? cars.Or(x => x.CarType== CarType.Limo)
: cars.And(x => x.CarType== CarType.Limo);
hasPassedFirstCheck = true;
}
if (filterObject.CarTypes.Contains(CarTypes.Race))
{
if (condition && !hasPassedFirstCheck)
cars = cars.And(x => x.CarType == CarType.Race);
else
cars = hasPassedFirstCheck
? cars.Or(x => x.CarType == CarType.Race)
: cars.And(x => x.CarType == CarType.Race);
hasPassedFirstCheck = true;
}
This also isn't really OOP. Any suggestion to refactor this is really appreciated.
condition
the same everywhere or is this simply a place holder for a check? If it's a random place holder then your question is off-topic because it is effectively pseudo code. It would be the best if the code to be reviewed would be compileable. \$\endgroup\$condition
was replaced with the real condition for the sake of simplicity and code that actually mattered. But I edited my post for those who think it's relevant. \$\endgroup\$