I wanted to transform the string "Employee.Orders.OrderID" in the linq expression: "employee.Orders.Select(order => order.OrderID)".
I already know how to do this in simple properties such as "Employee.FirstName" my question is how to do this in properties within a type within a collection.
"Order" is a collection of orders in the class "Employee". "OrderID" is a property of the class "Order".
In other words, I want to transform this;
string path = "Employee.Orders.OrderID";
Expression<Func<Employee, object>> exp = employee => employee.Orders.Select(order => order.OrderID);
This should do the trick:
I haven't compiled the resulting expression, but it builds the expression without an exception.
EDIT: I've added a line to create the lambda and compile it too, which it does, so it works.
It handles your scenario where you access a property of a collection
Orders.OrderID, which is the part that makes it sort of complicated. Without it, it would be about 30 lines shorter.
Currently, what it does is split the string on '.' and then it recursively processes every element. If the element is
IEnumerable (but not a string) it builds an additional
It also handles a slightly more complex (but more of the same) scenario where you access a collection property in a collection property.