3

我使用这段代码(在stackoverflow上找到)生成一个谓词

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

我怎样才能做到这一点 ?

谢谢,

4

2 回答 2

4

如果您使用的是字符串,则需要以困难的方式构建表达式:

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 上,我还使用 anExpressionVisitor重写“and”的主体,而不是Invoke; Invoke不支持 EF 等。

于 2012-06-29T05:55:18.023 回答
1
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");
于 2012-06-29T05:59:26.883 回答