Possible to convert IQueryable<Derived> to IQueryable<Base>?

戏子无情 提交于 2019-12-01 09:19:46

问题


I know about covariance, and I know that in general it will not be possible in C# until v4.0.

However I am wondering about a specific case. Is there some way of getting converting IQueryable<Derived> to IQueryable<Base> by somehow creating a wrapper class that does not actually perform a query, but can actually "pass through" a .Where<>() call?

My use case is that I am trying to deal with a database schema that has many similar tables. Most of the fields are in common, and many of the common fields need to be queried on each table. I'm using LinqToSql. I was hoping to avoid duplicating all the queries for each table.


回答1:


Is the following what you are looking for?

var results = queryable.OfType<Base>.Where(...);

The OfType method will gather up anything that is of the specified type, and if all items in the collection are either of type Base, or derived from type base, they should qualify. In the subsequent where, all items would be of type Base.




回答2:


The following will also work, altough it is less pretty:

var results = queryable.Select(derived => (Base)derived).Where(...);


来源:https://stackoverflow.com/questions/1474602/possible-to-convert-iqueryablederived-to-iqueryablebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!