gpt4 book ai didi

c# - 以字段名作为参数的表达式谓词

转载 作者:行者123 更新时间:2023-11-30 15:03:44 24 4
gpt4 key购买 nike

我使用这段代码(在 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

我该怎么做?

谢谢,

最佳答案

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

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重写“and”的主体,而不是 Invoke; EF 等不支持 Invoke

关于c# - 以字段名作为参数的表达式谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11256640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com