![](/img/trans.png)
[英]How can I convert lambda expression parameter type to another generic type?
[英]How can I convert a Parameter Expression into a function?
如果我有一個動態創建的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
用例,因為Where
和OrderBy
將有不同的實現 刪除以試圖縮小問題的范圍。
這是為OrderBy
和Where
生成表達式的示例。 正如 Johnathon Sullinger 在評論中所說,您必須知道在編譯時排序的屬性類型,因為它在OrderBY
簽名中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;
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.