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

我试图在运行时生成一个没有运气的简单Lambda表达式。

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

这是我的示例类和可查询的灯具:

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的建议!

1个解决方案
121 votes

在下面的查询中

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);
dtb answered 2020-07-31T06:15:11Z
translate from https://stackoverflow.com:/questions/8315819/expression-lambda-and-query-generation-at-runtime-simplest-where-example