I am working on a project and the situation I have encountered is that I need to "select" data from a queryable object. Unfortunately, I can not know what type that actual queryable object is at compile-time. So that I tried to invoke "select" method via reflection. The code I've tried so far is below.
....
.......
//suppose that I've got TSource and TResult at runtime.
Type argumentType = Model.GetArgumentType();
//get a queryable object from modle.
IEnumerable obj = Model.GetQueryableObject();
//looking for Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);
var selectMethod = typeof(System.Linq.Enumerable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(mi => mi.Name == "Select" &&
mi.GetParameters()[1].ParameterType.GetGenericArguments().Count() == 2)
.Single()
.MakeGenericMethod(new Type[] { argumentType, argumentType });
//that is where I have no idea how to do it
var result = selectMethod.Invoke(null, new object[] { obj, **xxxxxx** });
....
...
Can anyone tell me how can I make a "Func<TSource, TResult>" for the selectMethod to invoke "Select" method via reflection? Thanks.
Update:
As @Jon Skeet mentioned. There are several mistakes in example code. Apparently, I may asked the question in the wrong way (definitely it's all my fault). So that I decided to modify the original question to make it more clearly( or worse). Hope that helps.
(This answer was once only a comment.)
It would be something like
Type funcType = typeof(Func<,>).MakeGenericType(argumentType, argumentType);
(In a real situation you probably woldn't want TSource and TResult to be the same.)
After that, call Delegate.CreateDelegate with your funcType and whatever "select function" you want to put into your new delegate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With