How to write a dynamic linq method for Like
clause.
For reference, there is Dynamic LINQ OrderBy on IEnumerable<T>. I am looking for a similar one for dynamic Like
clause.
I have the following extension methods for like:
public static IQueryable<T> Like<T>(this IQueryable<T> source, string propertyName,
string keyword)
{
var type = typeof(T);
var property = type.GetProperty(propertyName);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var constant = Expression.Constant("%" + keyword + "%");
var methodExp = Expression.Call(
null,
typeof(SqlMethods).GetMethod("Like", new[] { typeof(string), typeof(string) }),
propertyAccess,
constant);
var lambda = Expression.Lambda<Func<T, bool>>(methodExp, parameter);
return source.Where(lambda);
}
The above method gives an error
Method 'Boolean Like(System.String, System.String)' cannot be used on the client; it is only for translation to SQL.
The other method which is somehow modified from Dynamic LINQ OrderBy on IEnumerable<T>:
public static IQueryable<T> ALike<T>(this IQueryable<T> source, string property,
string keyword)
{
string[] props = property.Split('.');
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
foreach (string prop in props)
{
// use reflection (not ComponentModel) to mirror LINQ
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
var constant = Expression.Constant("%" + keyword + "%");
var methodExp = Expression.Call(
null,
typeof(SqlMethods).GetMethod("Like", new[] { typeof(string), typeof(string) }),
expr,
constant);
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, methodExp, arg);
object result = typeof(Queryable).GetMethods().Single(
method => method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] { source, lambda });
return (IQueryable<T>)result;
}
The above method gives an error:
Expression of type 'System.Boolean' cannot be used for return type 'System.String'
Any ideas on this?
Something like:
You might also consider making it more reusable:
Are you aware of SqlMethods.Like ?
Had the same problem as you. SqlMethods.Like only works when executing on an SQL server, not on memory collections. So I have made a Like evaluator that will work, on collections - see my blog post here