IQueryable OfType<T> where T is a runtime Type

Tablet picture Tablet · Sep 8, 2010 · Viewed 10.1k times · Source

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.

Answer

Jon Skeet picture Jon Skeet · Sep 8, 2010

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.