Expression.Lambda and query generation at runtime, nested property “Where” example
Asked Answered
I

2

10

I found very nice answer on a question about building Expression Tree for Where query.

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

Can someone help me and show me how this example could be implemented in the scenario with nested property. I mean instead of:

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

With that solution:

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

How can I build the tree for the following?

var result = query.Where(item => item.Data.Name == "Soap").
Ibex answered 14/12, 2015 at 15:3 Comment(2)
What is Data? Specify this propertySoftware
Sergii thanks for help. I finally resolve that - you can check it below update. Second line is added and third is changed.Ibex
C
2

(This answer was originally posted by the OP in the question.)

The problem can be solved with:

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);
Changeless answered 14/12, 2015 at 15:3 Comment(0)
M
2

This is the same answer as posted above, but I find this more readable in terms of visualizing an expression tree:

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);
Modulate answered 14/12, 2015 at 17:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.