Reputation: 21206
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
}
Upvotes: 2
Views: 1390
Reputation: 35544
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();
Upvotes: 2