如何动态创建表达式<func <myclass,bool =“”>&gt;表达式<func <myclass,string =“”>&gt;谓词?</func <myclass,> </func <myclass,>

时间:2011-02-23 17:27:52

标签: c# linq expression-trees linq-expressions

我试图追加谓词和我的目标是创建相同的表达式:

Services.Where(s => s.Name == "Modules" && s.Namespace == "Namespace");

我有以下代码:

Expression<Func<Service,string>> sel1 = s => s.Name;
Expression<Func<Service,string>> sel2 = s => s.Namespace;

var val1 = Expression.Constant("Modules");
var val2 = Expression.Constant("Namespace");

Expression e1 = Expression.Equal(sel1.Body, val1);
Expression e2 = Expression.Equal(sel2.Body, val2);
var andExp = Expression.AndAlso(e1, e2);

ParameterExpression argParam = Expression.Parameter(typeof(string), "s");
var lambda = Expression.Lambda<Func<string, bool>>(andExp, argParam);

这会创建以下输出:

s => ((s.Name == "Modules") AndAlso (s.Namespace == "Namespace"))

但是,这是错误的,因为名称名称空间的参数不同。如果我将其中一个表达式选择器更改为:

Expression<Func<Service,string>> sel2 = srv => srv.Namespace;

输出将是:

s => ((s.Name == "Modules") AndAlso (srv.Namespace == "Namespace"))

如何使用 sel1 sel2 创建有效的表达式?

更新(2011年2月28日)

我通过创建调用表达式来解决它:Expression.Invoke所以lambda表达式sel1和sel2不一定需要是MemberExpression:

Expression<Func<Service,string>> sel1 = s => s.Name;
Expression<Func<Service,string>> sel2 = srv => srv.Namespace;

var val1 = Expression.Constant("Modules");
var val2 = Expression.Constant("Namespace");

Expression<Func<Service, bool>> lambda = m => true;
var modelParameter = lambda.Parameters.First();

// sel1 predicate
{
    var invokedExpr = Expression.Invoke(sel1, modelParameter);
    var binaryExpression = Expression.Equal(invokedExpr, val1);
    lambda = Expression.Lambda<Func<Service, bool>>(Expression.AndAlso(binaryExpression, lambda.Body), lambda.Parameters);
}
// sel2 predicate
{
    var invokedExpr = Expression.Invoke(sel2, modelParameter);
    var binaryExpression = Expression.Equal(invokedExpr, val2);
    lambda = Expression.Lambda<Func<Service, bool>>(Expression.AndAlso(binaryExpression, lambda.Body), lambda.Parameters);
}

2 个答案:

答案 0 :(得分:65)

很难混合编译器生成的表达式树和手工制作的表达式树,正是因为这种事情 - 提取出ParameterExpressions是棘手的。所以让我们从头开始:

ParameterExpression argParam = Expression.Parameter(typeof(Service), "s");
Expression nameProperty = Expression.Property(argParam, "Name");
Expression namespaceProperty = Expression.Property(argParam, "Namespace");

var val1 = Expression.Constant("Modules");
var val2 = Expression.Constant("Namespace");

Expression e1 = Expression.Equal(nameProperty, val1);
Expression e2 = Expression.Equal(namespaceProperty, val2);
var andExp = Expression.AndAlso(e1, e2);

var lambda = Expression.Lambda<Func<Service, bool>>(andExp, argParam);

我改变的一个重要方面是传递给Expression.Parameter的类型 - 当然看起来就像它应该是Service而不是string

我已经尝试了一下,当我调用lambda.Compile并在几个示例Service对象上执行它时,它似乎有效......

答案 1 :(得分:3)

您可以为可空类型创建表达式树,假设您有一个可以为空的字段BoardId,您可以像这样动态创建表达式树

  

var nameValue =&#34; BoardId = 111&#34 ;;

您需要确定第一个属性类型,无论其是否为Nullable

下面的代码为可为空和不可为空的类型创建动态树表达式

 public static Expression<Func<T, bool>> BuildWhereExpression<T>(string nameValueQuery ) where  T : class 
        {
            Expression<Func<T, bool>> predicate = null;
            PropertyInfo prop = null;
            var fieldName = nameValueQuery.Split("=")[0];
            var fieldValue = nameValueQuery.Split("=")[1];
            var properties = typeof(T).GetProperties();
            foreach (var property in properties)
            {
                if (property.Name.ToLower() == fieldName.ToLower())
                {
                    prop = property;
                }
            } 
            if (prop != null)
            {
                var isNullable = prop.PropertyType.IsNullableType();
                var parameter = Expression.Parameter(typeof(T), "x");
                var member = Expression.Property(parameter, fieldName); 

                if (isNullable)
                {
                    var filter1 =
                        Expression.Constant(
                            Convert.ChangeType(fieldValue, member.Type.GetGenericArguments()[0]));
                    Expression typeFilter = Expression.Convert(filter1, member.Type);
                    var body = Expression.Equal(member, typeFilter);  
                    predicate = Expression.Lambda<Func<T, bool>>(body, parameter);  
                }
                else
                {
                    if (prop.PropertyType == typeof(string) && likeOerator.ToLower() == "like")
                    {
                        var parameterExp = Expression.Parameter(typeof(T), "type");
                        var propertyExp = Expression.Property(parameterExp, prop);
                        MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
                        var someValue = Expression.Constant(fieldValue, typeof(string));
                        var containsMethodExp = Expression.Call(propertyExp, method, someValue);
                        predicate = Expression.Lambda<Func<T, bool>>(containsMethodExp, parameterExp);
                    }
                    else
                    {
                        var constant = Expression.Constant(Convert.ChangeType(fieldValue, prop.PropertyType));
                        var body = Expression.Equal(member, constant);  
                        predicate = Expression.Lambda<Func<T, bool>>(body, parameter); `enter code here`
                    }
                }
            }
            return predicate;
        }

1-此解决方案首先检查Nullable值并生成表达式。 这是如何确定类型是否为Nullable。我为此创建了一个扩展方法

  public static bool IsNullableType(this Type type) {  return
    type.IsGenericType &&
    (type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))); }

2-第二步是检查类型是否为其字符串,然后为字符串创建表达式。

3-第三步是检查值是否为空而不是字符串然后使用相等

创建表达式