有任何人得到了如何创建使用LINQ表达式一个。载(串)的功能,或者甚至创建谓词来完成这一点的想法

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

东西simular此将是理想的?

有帮助吗?

解决方案

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

其他提示

我用类似的东西,其中I添加过滤器到查询。

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

使用,应用过滤器的针对其名称匹配密钥的属性,并使用提供的值,值

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

通过具有2个的那些实例中,可以更容易地理解如何可以通过名字呼叫的各种不同的方法。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top