Expression.Lambda和运行时的查询生成,最简单的"其中"例

时间:2011-11-29 18:30:01

标签: c# .net lambda expression-trees dynamic-language-runtime

我试图在运行时生成一个简单的Lambda Expression而没有运气......就像这样:

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 提供建议!

1 个答案:

答案 0 :(得分:118)

在以下查询中

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);