Expression.Lambda和查询生成在运行时,最简单的“Where”示例

我试图在运行时生成一个简单的Lambdaexpression式,没有运气…像这样的东西:

var result = queryableData.Where(item => item.Name == "Soap") 

这是我的例子类和夹具查询:

 public class Item { public int Id { get; set; } public string Name { get; set; } } IQueryable<Item> queryableData = ...; 

然后我在运行时生成一个lambdaexpression式, 正确的代码如下

 //"item" in "item =>..." var item = Expression .Parameter(typeof(Item), "item"); //property of my item, this is "item.Name" var prop = Expression .Property(item, "Name"); //then "Soap" in '... => item.Name=="Soap"' var value = Expression.Constant("Soap"); //equality expression "==" in my primer var equals = Expression.Equal(prop, value); //then lambda var lambda = Expression.Lambda<Func<Item, bool>>(equals, item); //and here are the results var results = queryableData.Where(lambda); 

非常感谢dtb的build议!

在下面的查询中

 var result = query.Where(item => item.Name == "Soap") 

lambdaexpression式是

 item => item.Name == "Soap" 

你只需要构build这个部分,而不是接受expression式树的Where调用。

lambdaexpression式的expression式如下所示:

  Lambda / \ Equal Parameter / \ item Property \ "Name" Constant | "Soap" Parameter item 

在代码中:

 var item = Expression.Parameter(typeof(Item), "item"); var prop = Expression.Property(item, "Name"); var soap = Expression.Constant("Soap"); var equal = Expression.Equal(prop, soap); var lambda = Expression.Lambda<Func<Item, bool>>(equal, item); var result = queryableData.Where(lambda);