How can I build an ExpressionFuncMyClass, bool>> predicate dynamically from an ExpressionFuncMyClass, string>> predicate?

c# expression-trees linq linq-expressions

Question

My aim is to produce the same expression as: I'm attempting to add where predicates.

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

I own the next code:

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);

The results are as follows:

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

The parameter for Name and Namespace aren't the same, hence this is flawed. If one of the expression selectors is changed to:

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

Input will result in:

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

How can I utilize the numbers sel1 and sel2 to make an acceptable expression?

UPDATE (28 feb 2011)

I found a solution by developing invoke expressions:Expression.Invoke Thus, MemberExpression is not always required for the lambda expressions sel1 and sel2.

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);
}
1
41
12/29/2011 8:19:29 AM

Accepted Answer

It's challenging to separate the ParameterExpressions when combining compiler-generated and manually-created expression trees due of this kind of issue. So let's begin from the beginning:

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);

The type given to is a crucial adjustment I made.Expression.Parameter There is no doubt that it should be aService alternative to astring .

I tried it, and when I phoned, it appeared to work.lambda.Compile then put it to use on a few example cases.Service objects...

70
2/23/2011 5:44:04 PM

Popular Answer

If you have a nullable field named BoardId, you may generate an expression tree for nullable types by doing so in a dynamic way.

var nameValue="BoardId=111";

To start, you must ascertain the property type and if it is nullable or not.

The code below creates a dynamic tree expression for types that are nullable and non-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: Before generating the expression, this solution first checks for the nullable value. You can tell whether a type is nullable in this way. To do that, I developed an extension mechanism.

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

2. Create an expression for a string after determining if the type is string in step two.

3. The third step is to make sure the value is not a string or a nullable value before creating an expression using equal.



Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow