Skip to content

Instantly share code, notes, and snippets.

@vendettamit
Created February 11, 2016 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vendettamit/bb807b5da58599e0cdfa to your computer and use it in GitHub Desktop.
Save vendettamit/bb807b5da58599e0cdfa to your computer and use it in GitHub Desktop.
Build a expression dynamically with the Type that only be known at runtimes.
public static class QueryableExtension
{
public static dynamic Build<Tobject>(this Tobject source, string propertyName)
{
var propInfo = typeof(Tobject).GetProperty(propertyName);
var parameter = Expression.Parameter(typeof(Tobject), "x");
var property = Expression.Property(parameter, propInfo);
var delegateType = typeof(Func<,>).MakeGenericType(typeof(Tobject), propInfo.PropertyType);
var lambda = GetExpressionLambdaMethod().MakeGenericMethod(delegateType).Invoke(null, new object[] { property, new[] { parameter } });
return lambda;
}
private static MethodInfo GetExpressionLambdaMethod()
{
return typeof(Expression)
.GetMethods()
.Where(m => m.Name == "Lambda")
.Select(m => new
{
Method = m,
Params = m.GetParameters(),
Args = m.GetGenericArguments()
})
.Where(x => x.Params.Length == 2
&& x.Args.Length == 1
)
.Select(x => x.Method)
.First();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment