I\'m in the process of creating a more elaborate filtering system for this huge project of ours. One of the main predicates is being able to pass comparations through a string p
One of the at-first-glance-magical features of the C# compiler can do the hard work for you. You probably know you can do this:
Func totalCostIsUnder50 = d => d < 50m;
that is, use a lambda expression to assign a Func
. But did you know you can also do this:
Expression> totalCostIsUnder50Expression = d => d < 50m;
that is, use a lambda expression to assign an Expression
that expresses a Func
? It's pretty neat.
Given you say
The comparison builder is not the issue, that's the easy bit. The hard part is actually returning the expression
I'm assuming you can fill in the blanks here; suppose we pass in `"<50" to:
Expression> TotalCostCheckerBuilder(string criterion)
{
// Split criterion into operator and value
// when operator is < do this:
return d => d < value;
// when operator is > do this:
return d => d > value;
// and so on
}
Finally, to compose your Expression
s together with &&
(and still have an Expression
), do this:
var andExpression = Expression.And(firstExpression, secondExpression);