Create a new expression from an existing expression

I have. Expression<Func<T,DateTime>>I want to take part of a DateTime expression and pull out a month. So I would turn it into Expression<Func<T,int>>. I'm not quite sure how to do this. I looked at ExpressionTree Visitor , but I can't get it to work the way I need. The following is an example of a DateTime expression

DateTimeExpression http://img442.imageshack.us/img442/6545/datetimeexpression.png

Here is an example of what I want to create MonthExpression http://img203.imageshack.us/img203/8013/datetimemonthexpression.png

It looks like I need to create a new MemberExpression consisting of the Month property from a DateTime expression, but I'm not sure.

+5
source share
1 answer

Yes, exactly what you want - and using Expression.Property, this is the easiest way to do this:

Expression func = Expression.Property(existingFunc.Body, "Month");
Expression<Func<T, int>> lambda = 
    Expression.Lambda<Func<T, int>>(func, existingFunc.Parameters);

I believe that everything should be fine. It works in this simple test:

using System;
using System.Linq.Expressions;

class Person
{
    public DateTime Birthday { get; set; }
}

class Test
{
    static void Main()
    {
        Person jon = new Person 
        { 
            Birthday = new DateTime(1976, 6, 19)
        };

        Expression<Func<Person,DateTime>> dateTimeExtract = p => p.Birthday;
        var monthExtract = ExtractMonth(dateTimeExtract);
        var compiled = monthExtract.Compile();
        Console.WriteLine(compiled(jon));
    }

    static Expression<Func<T,int>> ExtractMonth<T>
        (Expression<Func<T,DateTime>> existingFunc)
    {
        Expression func = Expression.Property(existingFunc.Body, "Month");
        Expression<Func<T, int>> lambda = 
            Expression.Lambda<Func<T, int>>(func, existingFunc.Parameters);
        return lambda;
    }                                        
}
+8
source

All Articles