Skip to content

Instantly share code, notes, and snippets.

@OzieWest
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save OzieWest/2b38c92ab0bd96650e9a to your computer and use it in GitHub Desktop.

Select an option

Save OzieWest/2b38c92ab0bd96650e9a to your computer and use it in GitHub Desktop.
Snippets
public Func<T,T> AsProjections<T>(string fields) where T: class
{
var xParameter = Expression.Parameter(typeof(T), "o");
var xNew = Expression.New(typeof(T));
var bindings = fields.Split('.')
.Select(o => o.Trim())
.Select(o =>
{
var mi = typeof(T).GetProperty(o);
var xOriginal = Expression.Property(xParameter, mi);
return Expression.Bind(mi, xOriginal);
}
);
var xInit = Expression.MemberInit(xNew, bindings);
var lambda = Expression.Lambda<Func<T,T>>(xInit, xParameter);
return lambda.Compile();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment