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

c# dynamic-linq expression-trees lambda linq

Question

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);
1
2
11/26/2012 1:25:09 PM

Accepted Answer

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.

2
11/26/2012 5:31:16 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow