Based on my question from yesterday:
if I had to append to my existing \'where\' expression, how would i append?
Expression
I believe you can just do the following:
Expression> clientWhere = c => true;
if (filterByClientFName)
{
var prefix = clientWhere.Compile();
clientWhere = c => prefix(c) && c.ClientFName == searchForClientFName;
}
if (filterByClientLName)
{
var prefix = clientWhere.Compile();
clientWhere = c => prefix(c) && c.ClientLName == searchForClientLName;
}
If you need to keep everything in Expression-land (to use with IQueryable), you could also do the following:
Expression> clientWhere = c => true;
if (filterByClientFName)
{
Expression> newPred =
c => c.ClientFName == searchForClientFName;
clientWhere = Expression.Lambda>(
Expression.AndAlso(clientWhere, newPred), clientWhere.Parameters);
}
if (filterByClientLName)
{
Expression> newPred =
c => c.ClientLName == searchForClientLName;
clientWhere = Expression.Lambda>(
Expression.AndAlso(clientWhere, newPred), clientWhere.Parameters);
}
This can be made less verbose by defining this extension method:
public static Expression AndAlso(this Expression left, Expression right)
{
return Expression.Lambda(Expression.AndAlso(left, right), left.Parameters);
}
You can then use syntax like this:
Expression> clientWhere = c => true;
if (filterByClientFName)
{
clientWhere = clientWhere.AndAlso(c => c.ClientFName == searchForClientFName);
}
if (filterByClientLName)
{
clientWhere = clientWhere.AndAlso(c => c.ClientLName == searchForClientLName);
}