Search code examples
c#castingentity-framework-ctp5

IQueryable<T> cast to IList<SpecificInterface>


Setup

public interface ITable { }

public class Company : ITable {
    public int Id { get; set; }
    public string Name { get; set; }
}

public class PaginationGridModel {

    public PaginationGridModel(IList<ITable> rows) {
        //cool stuff goes here
    }
}

public GridModel GenerateModel<T>(IQueryable<T> Table) where T : ITable {
    return new GridModel((IList<ITable>)Table);
}

//Actual Call
return GenerateModel<Company>(this.dataContext.Companies);

Exception Generated

Unable to cast object of type 'System.Collections.Generic.List`1[Company]' to type 'System.Collections.Generic.IList`1[ITable]'.

Question

Since Company implements ITable I should be able to convert my List<Company> into an IList<ITable> however it doesn't want to work because it's actually T. But T is constrained in the function definition to an ITable. What am I doing wrong here? When I'm not using Generics the setup works just fine. However I wanted a Generic setup because I've been writing the same code over and over - which is bad :)

Any help would be greatly appreciated. Even if what you tell me is that it can't be done.


Solution

  • For .NET 3.5 you can use this:

    return new GridModel(table.ToList().ConvertAll(x => (ITable)x));