表达式谓词以字段名称为参数 [英] Expression predicates with field name as parameter
本文介绍了表达式谓词以字段名称为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用这段代码(在stackoverflow上找到)来生成谓词
I use this piece of code (found on stackoverflow) to generate a predicate
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
替换为(如果可能)
I'd like avoid, the switch and replace e => e.FirstName.StartWith
by (if possible)
e => e.fieldname.StartWith
我该怎么做?
谢谢
推荐答案
如果您使用的是字符串,则需要通过以下方式构建表达式:
If you are using strings, you need to build the expression the hard way:
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
; EF等不支持Invoke
.
On 4.0, I'd also have used an ExpressionVisitor
to rewrite the body for the "and", rather than an Invoke
; Invoke
is not supported on EF etc.
这篇关于表达式谓词以字段名称为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文