DateTime lambda expressions

c# expression expression-trees lambda linq-expressions

Question

I was testing the implementation in the thread answer https://stackoverflow.com/a/7891426/1468492 but I get an error trying to parse an expression with a DateTime, for instance: t => t.Name == "NAME" && t.OpeningDate == DateTime.Now.

Is this the right way to build a DateTime lambda expression? If I create an expression like Expression<Func<Model, bool>> expression = t => t.Name == "NAME" the result is correct.

Is there something wrong?

Accepted Answer

If you can build t => t.Name == "NAME" expression, the next step is to combine it with t.OpeningDate == DateTime.Now by Expression.And. Try this code:

var t = Expression.Parameter(typeof(Model), "t");
var body = Expression.And(
    Expression.Equal(Expression.PropertyOrField(t, "Name"), Expression.Constant("NAME")),
    Expression.Equal(Expression.PropertyOrField(t, "OpeningDate"), Expression.Constant(DateTime.Now))
);
var predicate = Expression.Lambda<Func<Model, bool>>(body, t);

Popular Answer

You need to improve current solution to support members, particularly you need to improve VisitMember. Now it just throws a NotSupportedException.

As a workaround you can just extract it first:

DateTime now = DateTime.Now;
var expression = t => t.Name == "NAME" && t.OpeningDate == now;

In this case it would address a constant, not a member.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why