Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Generic Class instance based on Anonymous Type

I have a class ReportingComponent<T>, which has the constructor:

public ReportingComponent(IQueryable<T> query) {}

I have Linq Query against the Northwind Database,

var query = context.Order_Details.Select(a => new 
{ 
    a.OrderID, 
    a.Product.ProductName,
    a.Order.OrderDate
});

Query is of type IQueryable<a'>, where a' is an anonymous type.

I want to pass query to ReportingComponent to create a new instance.

What is the best way to do this?

Kind regards.

like image 800
SharePoint Newbie Avatar asked Nov 11 '08 06:11

SharePoint Newbie


1 Answers

Write a generic method and use type inference. I often find this works well if you create a static nongeneric class with the same name as the generic one:

public static class ReportingComponent
{
  public static ReportingComponent<T> CreateInstance<T> (IQueryable<T> query)
  {
    return new ReportingComponent<T>(query);
  }
}

Then in your other code you can call:

var report = ReportingComponent.CreateInstance(query);

EDIT: The reason we need a non-generic type is that type inference only occurs for generic methods - i.e. a method which introduces a new type parameter. We can't put that in the generic type, as we'd still have to be able to specify the generic type in order to call the method, which defeats the whole point :)

I have a blog post which goes into more details.

like image 149
Jon Skeet Avatar answered Oct 23 '22 02:10

Jon Skeet