Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IQueryable OfType<T> where T is a runtime Type

I need to be able to get something similar to the following to work:

Type type = ??? // something decided at runtime with .GetType or typeof; object[] entityList = context.Resources.OfType<type>().ToList(); 

Is this possible? I am able to use .NET 4 if anything new in that allows this.

like image 607
Tablet Avatar asked Sep 08 '10 16:09

Tablet


2 Answers

You can call it by reflection:

MethodInfo method = typeof(Queryable).GetMethod("OfType"); MethodInfo generic = method.MakeGenericMethod(new Type[]{ type }); // Use .NET 4 covariance var result = (IEnumerable<object>) generic.Invoke       (null, new object[] { context.Resources }); object[] array = result.ToArray(); 

An alternative would be to write your own OfTypeAndToArray generic method to do both bits of it, but the above should work.

like image 105
Jon Skeet Avatar answered Sep 18 '22 15:09

Jon Skeet


Looks like you’ll need to use Reflection here...

public static IEnumerable<object> DyamicOfType<T>(         this IQueryable<T> input, Type type) {     var ofType = typeof(Queryable).GetMethod("OfType",                      BindingFlags.Static | BindingFlags.Public);     var ofTypeT = ofType.MakeGenericMethod(type);     return (IEnumerable<object>) ofTypeT.Invoke(null, new object[] { input }); }  Type type = // ...; var entityList = context.Resources.DynamicOfType(type).ToList(); 
like image 35
Timwi Avatar answered Sep 18 '22 15:09

Timwi