我用这段代码(#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
我怎样才能做到这一点 ?
谢谢,