Luis
Luis

Reputation: 87

How to create a property (collection) expression selector from a string?

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

Into this;

Expression<Func<Employee, object>> exp = employee => employee.Orders.Select(order => order.OrderID);

Upvotes: 3

Views: 1261

Answers (1)

JulianR
JulianR

Reputation: 16513

This should do the trick:

https://gist.github.com/4149424

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 Select lambda.

It also handles a slightly more complex (but more of the same) scenario where you access a collection property in a collection property.

Upvotes: 3

Related Questions