2

I want to build a query with where condition for filter properties when they have a value (not null). The multiple filters must be a AND combination if they are used.

How can combine/add each predicate when the according property value is not null to get a final query ready for filtering?

IQueryable<Customer> filter = null;

Expression<Func<Customer, bool>> predicatetest1 = res => res.test1 == request.test1;
Expression<Func<Customer, bool>> predicatetest2 = res => res.test2 == request.test2;
Expression<Func<Customer, bool>> predicatetest3 = res => res.test3 == request.test3;

if (request.test1 != null)
{
     // add the above predicate to the filter
}

if (request.test2 != null)
{
    // add the above predicate to the filter
}

if (request.test3 != null)
{
   // add the above predicate to the filter
}
Elisabeth
  • 20,496
  • 52
  • 200
  • 321

1 Answers1

1
IQueryable<Customer> filter = Context.Customers;

if (request.test1 != null)
{
  filter = filter.Where(predicatetest1);
}

if (request.test2 != null)
{
  filter = filter.Where(predicatetest2);
}

if (request.test3 != null)
{
  filter = filter.Where(predicatetest3);
}

var customers = filter.ToList();

The following would be equivalent, when all 3 properties where not null

Context.Customers.Where(predicatetest1).Where(predicatetest2).Where(predicatetest3).ToList();
Jehof
  • 34,674
  • 10
  • 123
  • 155
  • When all 3 properties are not null this would always overwrite the before set filter. I want that all 3 filters are used in a AND style. – Elisabeth Nov 13 '15 at 13:07
  • @Elisabeth No, this will chain the Where methods resulting in AND style. – Jehof Nov 13 '15 at 13:08
  • @Elisabeth the return value of Where is an IQueryable. So base query+where – Jehof Nov 13 '15 at 13:14
  • And all the 3 Where methods are executed as predicate1 AND predicate2 AND predicate3 ? 3 separated Where are an "OR" actually right? – Elisabeth Nov 13 '15 at 13:14
  • But I need the AND over all predicates as I wrote above. :-) Do I need the PredicateBuilder for this? – Elisabeth Nov 13 '15 at 13:15
  • @Elisabeth This is AND chaining – Jehof Nov 13 '15 at 13:16
  • Can I see that somehow while debugging that it is an AND? :-) – Elisabeth Nov 13 '15 at 13:28
  • Now that I have read this: http://stackoverflow.com/questions/252785/what-is-the-difference-between-iqueryablet-and-ienumerablet?rq=1 am I correct that I do not need IQueryable at all, just IEnumerable which would also execute only on ToList()? – Elisabeth Nov 13 '15 at 20:13