Skip to content

Instantly share code, notes, and snippets.

@BrannJoly
Created August 5, 2015 15:47
Show Gist options
  • Save BrannJoly/b7555fa4c150253ad5ee to your computer and use it in GitHub Desktop.
Save BrannJoly/b7555fa4c150253ad5ee to your computer and use it in GitHub Desktop.
/// <summary>
/// Generates an Expression that can set a nested property
/// </summary>
/// <param name="path">a list of nested properties </param>
/// <returns>the compiled set expression</returns>
public Expression<Action<T, object>> CreateNestedSet(List<string> path)
{
// target
var targetParameterExpression = Expression.Parameter(typeof(T), "target");
// target.nested.path
var propertyExpression = path.Aggregate<string, Expression>(targetParameterExpression, (c, m) => Expression.Property(c, m));
//value
var valueParameterExpression = Expression.Parameter(typeof(object), "value");
// (type) value;
var castedValueExpression = Expression.Convert(valueParameterExpression, propertyExpression.Type);
//target.nested.path = (type) value
var assignExpression = Expression.Assign(propertyExpression, castedValueExpression);
// (target, value) => target.nested.path = (type) value;
var assign = Expression.Lambda<Action<T, object>>(assignExpression,targetParameterExpression, valueParameterExpression);
return assign;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment