Is there any way of breaking up an Expression<Func<T, Bool>> and get the right hand side of the equality comparison?
c#, equality, expression, lambda, linq
Solution
Expression<Func<Foo, bool>> expr = p => p.Id == 2; // Supports even p.Id.Equals(2)
BinaryExpression be = expr.Body as BinaryExpression;
if (be != null)
{
Expression left = be.Left;
Expression right = be.Right;
}
else
{
MethodCallExpression mc = expr.Body as MethodCallExpression;
if (mc != null && mc.Method.Name == "Equals" && mc.Arguments.Count == 1)
{
Expression obj = mc.Object; // "left"
Expression arg = mc.Arguments[0]; // "right"
}
else
{
// not supported
}
}
Here it is...
Note that this will work only in the most simple case, where there is a simple `BinaryExpression` and `MethodCallExpression` with `Equals`.
But if for example the expression is:
Expression<Func<Foo, bool>> expr = p => true;
or...
Expression<Func<Foo, bool>> expr = p => p.Id == 2 && something;
Then it won't work.
Problem
This may be a longshot, but I will try it anyway. Let's say that I have an expression in these manners: ``` public class Foo { public int Id { get; set; } } Expression<Func<Foo, bool>> expr = p => p.Id == 2; ``` Is there any way of breaking up the expression, by let's say: Get the member name (expr.Body as MemberExpression).Member.Name; And get the right hand side value of the equality comparison. That is, the 2. Or is this not possible?