How do I dynamically create an Expression> predicate from Expression>?

后端 未结 2 2116
误落风尘
误落风尘 2020-11-29 22:50

I trying to append where predicates and my goal is to create the same expression as:

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


        
2条回答
  •  臣服心动
    2020-11-29 23:32

    It's hard to mix compiler-generated expression trees and hand-made ones, precisely because of this sort of thing - extracting out the ParameterExpressions is tricky. So let's start from scratch:

    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>(andExp, argParam);
    

    One important aspect I've changed is the type passed to Expression.Parameter - it certainly looks like it should be a Service rather than a string.

    I've given that a try, and it seemed to work when I called lambda.Compile and executed it on a couple of sample Service objects...

提交回复
热议问题