Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional predicates in LINQ?

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();
}
like image 257
softwarematter Avatar asked Jan 31 '17 08:01

softwarematter


1 Answers

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());
like image 192
Patrick Hofman Avatar answered Sep 22 '22 03:09

Patrick Hofman