dimanche 12 août 2018

How to call IQueryable.OrderBy() method with a runtime type for generic parameter?

I need to call the OrderBy<T, TKey>(Func<T, TKey>) method with a value for TKey only available at runtime. After reading answers on SO on how to use a variable as a generic parameter, I'm trying the following approach:

string key = "MyProperty";
Type keyType = typeof(T).GetProperty(key).PropertyType;
MethodInfo methodInfo = typeof(MyClass)
                .GetMethod(
                    "MyGenericStaticMethod"),
                    BindingFlags.NonPublic | BindingFlags.Static);
// T is known at compile time.
MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(new[] { typeof(T), keyType});

var expression = genericMethodInfo.Invoke(null, new object[] { params });

myQueryable.OrderBy(expression);

The problem is, genericMethodInfo.Invoke() returns object and hence cannot be used with OrderBy() which expects an argument of type Func<T, TKey>. However, TKey can be different value types like string,int that are only known at runtime. Can this even be done and if so, how?





Aucun commentaire:

Enregistrer un commentaire