views:

42

answers:

0

I attempted to do this below, with mind blanks as it got complicated.

I need to build a predicate to pass to my Product Repository from a client string:

"fieldname .startsWith. 'fieldvalue'"
"fieldname .contains. 'fieldvalue'"
"fieldname .equals. 3"
"fieldname .greaterThan. 3"
"fieldname .lessThan. 3"

The field names could be any existing field in the Entity. It's there job to match them exactly. There are only numbers and string, and only the commands listed.

Code so far (wild flailing):

// p => p.L == R
// L is the left side (the field to examine)
// R is the right side (the value to compare to)
// O is the operator (Equal)

var fieldParm    = Expression.Parameter(typeof(Entity), typeof(Entity).Name);

var compareL1 = MemberExpression.Property(fieldParm, "fieldName"); // fieldname
var compareR1 = Expression.Constant("fieldValue");  // what field should equal
var compareO1 = MemberExpression.Equal(compareWhat, compareTo);

// Do it again for each one (probably should make a foreach out of this)
var compareL2 = MemberExpression.Property(fieldParm, "fieldName"); // fieldname
var compareR2 = Expression.Constant("fieldValue");  // what field should equal
var compareO2 = MemberExpression.Equal(compareWhat, compareTo);

// Put them all together
var myExpress = Expression.And(compareO1, compareO2) // And them together

// Create predicate
Expression<Func<Entity, bool>> resultLambda =
    Expression.Lambda<Func<Entity, bool>>( myExpress,
        new ParameterExpression[] { fieldParm });

And resultLambda should contain our predicate to pass to our .Where() clause

How would you do this for a series of AND conditions like above?