views:

143

answers:

1

Has anybody got an idea of how to create a .Contains(string) function using Linq Expressions, or even create a predicate to accomplish 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);
}

Something simular to this would be ideal?

+1  A: 
public static Expression<Func<string, bool>> StringContains(string subString)
{
    MethodInfo contains = typeof(string).GetMethod("Contains");
    ParameterExpression param = Expression.Parameter("s", typeof(string));
    return Expression.Call(param, contains, Expression.Constant(subString, typeof(string)));
}

...

// s => s.Contains("hello")
Expression<Func<string, bool>> predicate = StringContains("hello");
Thomas Levesque
Did the trick, thx
BK
Just to give some clarity, this solution mentioned above won't work if you use it directly, I only used some of the content like the MethodInfo and ParameterExpression.
BK