Created
February 11, 2016 16:21
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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