如何将参数表达式转换为函数?

时间:2018-09-16 00:50:23

标签: c# reflection types expression

如果我有一个动态创建的ParameterExpression

class Product
{
    public string Name { get; set; }
}

var propertyName = "Name";

var propertyType = typeof(Product).GetProperty(propertyName).PropertyType;
var parameterExpression = Expression.Parameter(propertyType , propertyName);

如何将其隐藏为Func<Product, TPropertyType>

我特别想将其传递给实体框架使用的 Where OrderBy linq方法。

我也对不使用Expressions的其他建议持开放态度,但我对此表示怀疑。

编辑1 :删除了where用例,因为WhereOrderBy将具有不同的实现,以缩小问题范围。

1 个答案:

答案 0 :(得分:1)

这里是为OrderByWhere生成表达式的示例。正如Johnathon Sullinger在评论中说的那样,您必须知道在编译时订购的属性的类型,因为它是在OrderBY的签名中提到的。但是,您不必为Where知道它:

class Product
{
    public string Name { get; set; }
}

static void Main(string[] args)
{
    var products = new List<Product> {
        new Product { Name = "ZZZ"},
        new Product { Name = "AAA"}
    };

    var propertyName = "Name";

    var ordered = products.AsQueryable().OrderBy(GetOrderExpression<string>(propertyName));
    Console.WriteLine(ordered.ElementAt(0).Name);
    Console.WriteLine(ordered.ElementAt(1).Name);

    var filtered = products.AsQueryable().Where(GetWhereExpression(propertyName, "AAA"));
    Console.WriteLine(filtered.Count());
    Console.WriteLine(filtered.ElementAt(0).Name);

    Console.ReadKey();
}

static Expression<Func<Product, TKey>> GetOrderExpression<TKey>(string propertyName)
{
    var prm = Expression.Parameter(typeof(Product), "p");
    var prop = Expression.Property(prm, typeof(Product), propertyName);
    var lambda = Expression.Lambda<Func<Product, TKey>>(prop, "p", new[] { prm });

    return lambda;
}

static Expression<Func<Product, bool>> GetWhereExpression(string propertyName, object value)
{
    var prm = Expression.Parameter(typeof(Product), "p");
    var prop = Expression.Property(prm, typeof(Product), propertyName);
    var equal = Expression.Equal(prop, Expression.Constant(value));
    var lambda = Expression.Lambda<Func<Product, bool>>(equal, "p", new[] { prm });

    return lambda;
}

希望有帮助。