ghanshyam.mirani
ghanshyam.mirani

Reputation: 3101

Issue related to Generics and Linq

I have got the list of Class Name as Follows:

Type[] typelist = typeof(Sample.Students).Assembly.GetTypes();

now i have complete list of all classes available in Sample NameSpace:

Now i want to get data through class I am using Devexpress Persistance class so basically i have to create XPQuert Object as follows:

XPQuery<Employee> EmployeeQuery = new  XPQuery<Employees>(XPODefault.Session);

but in my case Employee class will be listed in typelist variable.. How can i create the object of XPQuery.. is it possible something like this:

XPQuery<typeof(typelist[0].Name)> EMployeeQuery = new XPQuery<typeof(typelist.Name)> (XPODefault.Session);

i meant i want to create object dynamically.. how can i do Thanks..

Upvotes: 1

Views: 314

Answers (2)

Wouter de Kort
Wouter de Kort

Reputation: 39898

You can use reflection to dynamically construct a generic type.

Type queryType = typeof(XPQuery<>);
Type[] typeArgs = { typelist[0] };

Type constructed = queryType .MakeGenericType(typeArgs);
object myQuery = Activator.CreateInstance(constructed, XPODefault.Session);

You need to use the CreateInstance(type, params Object[] args) overload so you can specify the arguments needed for your constructor.

The only problem you have is that the returned type of CreateInstance is of type object. If you want to call any other methods on myQuery, you need to use reflection or the dynamic keyword.

Upvotes: 1

Alexey Raga
Alexey Raga

Reputation: 7525

You can do something like:

public static IQueryable CreateQueryInstance(Type queryType) 
{
    var genericQueryTypeDefinition = typeof(XPQuery<>);
    var queryTypeArguments = new[] { typeof(queryType) };
    var genericQueryType = genericQueryTypeDefinition.MakeGenericType(queryTypeArguments);
    var queryObject = (IQueryable)Activator.CreateInstance(genericQueryType, <your parameters here>);

    return queryObject;
}

And then use it as:

var myQueryObject = CreateQueryInstance(typelist[0]);

Of course you will NOT be able to have a nice XPQuery as you don't know the type at the compile time, but you still can have an IQueryable to start from.

Upvotes: 2

Related Questions