简体   繁体   中英

Dynamic expression “x => x.Date >= SomeDate”

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>>;

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>>;            
}

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM