Is there a way to combine the queries in if
and else
sections?
public List<MyClass> GetData(Category category, bool flag= true)
{
IQueryable<MyClass> result;
if (flag)
{
result = Session.All<MyClass>()
.Where(mc => mc.Col.Equals(category.ToString()) && mc.FLAG);
}
else
{
result = Session.All<MyClass>()
.Where(mc => mc.Col.Equals(category.ToString()));
}
return result.ToList();
}
Sure.
result = Session.All<MyClass>()
.Where(mc => mc.Col.Equals(category.ToString()) && (!flag || mc.FLAG));
You can determine the rewrite logic by making a matrix of allowed true
outcomes:
▼ mc.FLAG ► flag
true false
true valid valid
false invalid valid
Here you see that the condition is valid if flag
is false (both equate to true
) or mc.FLAG
is true
.
I would also advice to do the flag check first, since that is the better performing predicate. This might prevent the second check if the first results to false:
result = Session.All<MyClass>()
.Where(mc => (!flag || mc.FLAG) && mc.Col.Equals(category.ToString());
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