How do I build an expression that will fulfill the following goal:
public object Eval(object rootObj, string propertyString)
eg: Eval(pers
Here's a recursive version of p.s.w.g's code, working with Expressions
.
public Expression Eval(Expression expression, string property)
{
var split = property.Split('.');
if (split.Length == 1)
{
return Expression.PropertyOrField(expression, property);
}
else
{
return Eval(Expression.PropertyOrField(expression, split[0]), property.Replace(split[0] + ".", ""));
}
}
It sounds like you're looking for something like this:
public object Eval(object root, string propertyString)
{
var propertyNames = propertyString.Split('.');
foreach(var prop in propertyNames)
{
var property = root.GetType().GetProperty(prop);
if (property == null)
{
throw new Exception(...);
}
root = property.GetValue(root, null);
}
return root;
}
To create an Expression
use this:
public Expression Eval(object root, string propertyString)
{
var propertyNames = propertyString.Split('.');
ParameterExpression param = Expression.Parameter(root.GetType, "_");
Expression property = param;
foreach(var prop in propertyName)
{
property = Expression.PropertyOrField(property, prop);
}
return Expression.Lambda(property, param);
}