9

有没有人知道如何使用 Linq 表达式创建一个 .Contains(string) 函数,甚至创建一个谓词来完成这个

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);
}

与此类似的东西是理想的吗?

4

2 回答 2

5
public static Expression<Func<string, bool>> StringContains(string subString)
{
    MethodInfo contains = typeof(string).GetMethod("Contains");
    ParameterExpression param = Expression.Parameter(typeof(string), "s");
    var call = Expression.Call(param, contains, Expression.Constant(subString, typeof(string)));
    return Expression.Lambda<Func<string, bool>>(call, param);
}

...

// s => s.Contains("hello")
Expression<Func<string, bool>> predicate = StringContains("hello");

多年以后再看这个,我突然意识到这个具体例子有一个更简单的方法:

Expression<Func<string, bool>> predicate = s => s.Contains("hello");
于 2010-03-17T09:29:16.963 回答
4

我使用类似的东西,我在查询中添加过滤器。

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);
}

用法,对名称与 Key 匹配的属性应用过滤器,并使用提供的值 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));
}

是的,此方法适用于包含:

        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);
    }

通过这两个示例,您可以更轻松地理解我们如何通过名称调用各种不同的方法。

于 2015-11-24T17:55:41.777 回答