Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top