GetExpression Method
suggest changepublic static Expression<Func<T, bool>> GetExpression<T>(IList<QueryFilter> filters)
{
Expression exp = null;
// The parameter in { parm => ... }. T is the entity type and the name is fixed as "parm".
ParameterExpression param = Expression.Parameter(typeof(T), "parm");
// Do not trust the caller's list without checking it.
if (filters.Count == 0)
return null;
// One filter, two filters, and more than two filters are built differently.
// Removing items mutates the list passed by the caller.
if (filters.Count != 1)
{
if (filters.Count == 2)
// The private overloads are explained in another example.
exp = GetExpression<T>(param, filters[0], filters[1]);
else
{
// There is no overload for more than two filters, so fold them in two at a time.
while (filters.Count > 0)
{
// Retrieve the first two filters.
var f1 = filters[0];
var f2 = filters[1];
// AndAlso is a conditional AND: the second operand runs only when the first is true.
// It returns a BinaryExpression.
exp = exp == null ? GetExpression<T>(param, filters[0], filters[1]) : Expression.AndAlso(exp, GetExpression<T>(param, filters[0], filters[1]));
// Drop the two filters just used so the next iteration sees the rest.
filters.Remove(f1);
filters.Remove(f2);
// If one filter remains, AND it in and drop it.
if (filters.Count == 1)
{
exp = Expression.AndAlso(exp, GetExpression<T>(param, filters[0]));
filters.RemoveAt(0);
}
}
}
}
else
exp = GetExpression<T>(param, filters[0]);
// Convert the expression into a lambda and return the query.
return Expression.Lambda<Func<T, bool>>(exp, param);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents