表达式.运行时生成Lambda和查询,最简单的"Where"的例子
本文关键字:quot Where 最简单 运行时 Lambda 查询 表达式 | 更新日期: 2023-09-27 18:16:02
我试图在运行时生成一个简单的Lambda表达式,没有运气…像这样:
var result = queryableData.Where(item => item.Name == "Soap")
下面是我的示例类和fixture查询:
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
IQueryable<Item> queryableData = ...;
然后我在运行时生成一个lambda表达式正确的代码如下:
//"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的建议!
在以下查询
var result = query.Where(item => item.Name == "Soap")
lambda表达式是
item => item.Name == "Soap"
您只需要构造这一部分,而不需要构造接受表达式树的Where调用。
lambda表达式的表达式树如下所示:
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);