Expression.Lambda和运行时的查询生成,嵌套属性“Where”示例

时间:2015-12-14 15:03:35

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

我找到了关于为Where查询构建表达式树的问题的非常好的答案。

Expression.Lambda and query generation at runtime, simplest "Where" example

有人可以帮助我并告诉我如何在具有嵌套属性的场景中实现此示例。我的意思是代替:

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

使用该解决方案:

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

如何为以下内容构建树?

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

2 个答案:

答案 0 :(得分:2)

这与上面发布的答案相同,但我发现在可视化表达式树方面更具可读性:

var parameterItem = Expression.Parameter(typeof(Item), "item");

var lambda = Expression.Lambda<Func<Item, bool>>(
    Expression.Equal(
        Expression.Property(
            Expression.Property(
                parameterItem, 
                "Data"
            ), 
            "Name"
        ), 
        Expression.Constant("Soap")
    ), 
    parameterItem
);

var result = queryableData.Where(lambda);

答案 1 :(得分:1)

(这个答案最初是由OP在问题中发布的。)

问题可以通过以下方式解决:

var item = Expression.Parameter(typeof(Item), "item");

var dataExpr = Expression.Property(item, "Data");

var prop = Expression.Property(dataExpr, "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);