Question

I want to build the expression: x => x.Date >= SomeDate

But it the following code, all i can get is x => ( x.Date >= SomeDate ), which does not work at all, because of the parentheses I guess.

Expression<Func<T, DateTime>> expression = x => x.Date;

var date= new DateTime(2013, 8, 22);

ParameterExpression param = Expression.Parameter(typeof(T), "x");
Expression lambda = Expression.Lambda<Func<T, bool>>(
Expression.GreaterThanOrEqual(expression.Body,
Expression.Constant(date, typeof(DateTime))), param);

var valueExpression = lambda as Expression<Func<T, bool>>;
Was it helpful?

Solution

The problem with your code is that parameters in expressions are compared by reference, not by name. The simplest way to solve this in your case is to use the parameter from the original expression, instead of creating your own:

ParameterExpression param = expression.Parameters.Single();
var lambda = Expression.Lambda<Func<T, bool>>(
    Expression.GreaterThanOrEqual(expression.Body, Expression.Constant(date)),
    param);

OTHER TIPS

It seems to work fine for me, what kind of error do you get? Compile time/Runtime?

Remember that, for x.Date to work, the compiler must know the type T at compile time and that it actually contains a Date property.

I implemented this like:

internal interface ITClass
{
    DateTime Date { get; set; }
}

internal class TClass : ITClass
{
    public DateTime Date { get; set; }
}

and ...

private static void CompareDate<T>() where T : ITClass
{
    Expression<Func<T, DateTime>> expression = x => x.Date;

    var date = new DateTime(2013, 8, 22);

    var param = Expression.Parameter(typeof(T), "x");
    Expression lambda = Expression.Lambda<Func<T, bool>>(
    Expression.GreaterThanOrEqual(expression.Body,
    Expression.Constant(date, typeof(DateTime))), param);

    var valueExpression = lambda as Expression<Func<T, bool>>;            
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top