用字段名作为参数谓词表达(Expression predicates with field name

2019-09-18 17:33发布

我用这段代码(#1实测值),以产生一个谓语

static class BuilderPredicate
{
    public static Expression<Func<T, bool>> True<T>() { return f => true; }
    public static Expression<Func<T, bool>> False<T>() { return f => false; }

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

    public static Expression<Func<T, bool>> And<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.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
    }
}

我有这样的对象:

public class Person : IPerson
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public interface IPerson
{
    int Id { get; set; }
    string FirstName { get; set; }
    string LastName { get; set; }
}

要使用到,我这样做:

private void CreationPredicate(string fieldname, string stringToSearch)
{
    var predicate = BuilderPredicate.True<Person>();
    switch (fieldname)
    {
        case "FirstName":
            predicate = predicate.And(e => e.FirstName.StartsWith(stringToSearch));
            break;
        case "LastName":
            predicate = predicate.And(e => e.LastName.StartsWith(stringToSearch));
            break;
    }
}

我想避免,开关和替换e => e.FirstName.StartWith通过(如果可能)

e => e.fieldname.StartWith

我怎样才能做到这一点 ?

谢谢,

Answer 1:

如果您使用的字符串,你需要建立表达硬盘的方式:

var param = Expression.Parameter(typeof (Foo));
var pred = Expression.Lambda<Func<Foo, bool>>(
    Expression.Call(
        Expression.PropertyOrField(param, fieldName),
        "StartsWith",null,
        Expression.Constant(stringToSearch)), param);

在4.0中,我还使用了一个ExpressionVisitor 重写身体为“和”,而不是Invoke ; Invoke不支持EF等。



Answer 2:

delegate string StringPropertyGetter(IPerson person);

void CreationPredicate(StringPropertyGetter getter, string stringToSearch)
{
    var predicate = BuilderPredicate.True<Person>();
    predicate = predicate.And(e => getter(e).StartsWith(stringToSearch));
}

这样调用:

CreationPredicate(p => p.FirstName, "searchstring");


文章来源: Expression predicates with field name as parameter