IQueryable <T> discarded in IList <SpecificInterface>

Customization

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 thrown

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

Question

Since it Companyimplements ITable, I should be able to convert mine List<Company>to IList<ITable>, but it does not want to work, because it is actually T. But it is Tlimited in function definition to ITable. What am I doing wrong here? When I do not use Generics, the setup works fine. However, I need a Generic setup because I repeated the same code over and over - which is bad :)

Any help would be greatly appreciated. Even if you tell me this is not possible.

+3
source share
3 answers

For .NET 3.5 you can use this:

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

.NET 4.0, .

+1

You can also use the LINQ Cast () extension method:

return new GridModel((IList<ITable>)Table.Cast<T>());

which is a little clearer.

It is also better to use IEnumerable instead of IList, if possible.

0
source

Source: https://habr.com/ru/post/1794241/


All Articles