【问题标题】:Create New Expression from Existing Expression从现有表达式创建新表达式
【发布时间】:2010-03-04 07:14:30
【问题描述】:

我有一个Expression<Func<T,DateTime>> 我想从表达式中取出 DateTime 部分并从中提取月份。所以我会把它变成Expression<Func<T,int>> 我不太确定该怎么做。我查看了ExpressionTree Visitor,但我无法让它像我需要的那样工作。这是 DateTime 表达式的示例

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

这是我想要创建的示例 MonthExpression http://img203.imageshack.us/img203/8013/datetimemonthexpression.png

看起来我需要创建一个新的 MemberExpression,它由 DateTime 表达式中的 Month 属性组成,但我不确定。

【问题讨论】:

  • 我在哪里可以获得您正在使用的表达式树查看器?它适用于 Visual Studio 2010 吗?
  • 它带有 Linq 示例。这里有一个很好的例子linqinaction.net/blogs/jwooley/archive/2008/08/24/…我没有在 Studio 2010 中尝试过,但我知道它在 2008 年可以使用。

标签: c# .net lambda expression-trees expression


【解决方案1】:

是的,这正是您想要的 - 使用 Expression.Property 是最简单的方法:

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

我相信应该没问题。它适用于这个简单的测试:

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

【讨论】:

  • 完美运行。谢谢乔恩。
猜你喜欢
  • 2010-10-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多