LINQ expression <Func <T, bool >> equavalent.Contains ()
Has anyone got an idea on how to create a .Contains (string) function using Linq expressions or create a predicate to execute this
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>()); return Expression.Lambda<Func<T, bool>> (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters); } Would something like this be perfect?
+7
BK.
source share2 answers
public static Expression<Func<string, bool>> StringContains(string subString) { MethodInfo contains = typeof(string).GetMethod("Contains"); ParameterExpression param = Expression.Parameter(typeof(string), "s"); return Expression.Call(param, contains, Expression.Constant(subString, typeof(string))); } ... // s => s.Contains("hello") Expression<Func<string, bool>> predicate = StringContains("hello"); +6
Thomas levesque
source shareI use something similar where I add filters to the query.
public static Expression<Func<TypeOfParent, bool>> PropertyStartsWith<TypeOfParent, TypeOfPropery>(PropertyInfo property, TypeOfPropery value) { var parent = Expression.Parameter(typeof(TypeOfParent)); MethodInfo method = typeof(string).GetMethod("StartsWith",new Type[] { typeof(TypeOfPropery) }); var expressionBody = Expression.Call(Expression.Property(parent, property), method, Expression.Constant(value)); return Expression.Lambda<Func<TypeOfParent, bool>>(expressionBody, parent); } Use to apply a filter to a property whose name matches the key, and using the provided value, value.
public static IQueryable<T> ApplyParameters<T>(this IQueryable<T> query, List<GridParameter> gridParameters) { // Foreach Parameter in List // If Filter Operation is StartsWith var propertyInfo = typeof(T).GetProperty(parameter.Key); query = query.Where(PropertyStartsWith<T, string>(propertyInfo, parameter.Value)); } And yes, this method works with contains:
public static Expression<Func<TypeOfParent, bool>> PropertyContains<TypeOfParent, TypeOfPropery>(PropertyInfo property, TypeOfPropery value) { var parent = Expression.Parameter(typeof(TypeOfParent)); MethodInfo method = typeof(string).GetMethod("Contains", new Type[] { typeof(TypeOfPropery) }); var expressionBody = Expression.Call(Expression.Property(parent, property), method, Expression.Constant(value)); return Expression.Lambda<Func<TypeOfParent, bool>>(expressionBody, parent); } With these 2 examples, you can more easily understand how we can name the various methods by name.
+1
Greg
source share