I have a Linq extension method to dynamically filter Linq queries using string values. For example: query.WhereHelper("columName", ">", 1)
. I could use many different filter operators like GreaterThan or NotEqual etc. but not "Like". There is no Expression.Like or Expression.StartsWith etc. How can I implement Like operator to my Expression tree? Here's my code:
public static IQueryable<T> WhereHelper<T>(this IQueryable<T> source, string columnName, object value, string filterType)
{
ParameterExpression table = Expression.Parameter(typeof(T), "");
Expression column = Expression.PropertyOrField(table, columnName);
Expression valueExpression = Expression.Convert(Expression.Constant(value), column.Type);
Expression where = null;
switch (filterType)
{
case "<":
where = Expression.LessThan(column, valueExpression);
break;
case "<=":
where = Expression.LessThanOrEqual(column, valueExpression);
break;
case "=":
where = Expression.Equal(column, valueExpression);
break;
case ">":
where = Expression.GreaterThan(column, valueExpression;
break;
case ">=":
where = Expression.GreaterThanOrEqual(column, valueExpression);
break;
case "<>":
where = Expression.NotEqual(column, valueExpression);
break;
}
Expression lambda = Expression.Lambda(where, new ParameterExpression[] { table });
Type[] exprArgTypes = { source.ElementType };
MethodCallExpression methodCall = Expression.Call(typeof(Queryable),
"Where",
exprArgTypes,
source.Expression,
lambda);
return (IQueryable<T>)source.Provider.CreateQuery<T>(methodCall);