How to combine 2different IQueryable/List/Collection with same base class? LINQ Union and Covariance issues

社会主义新天地 提交于 2019-11-28 13:22:16
Stephen Cleary

Use the Cast operator:

IQueryable<ItemBase> folderItems = contractItems
        .Cast<ItemBase>()
        .Concat(changeOrderItems.Cast<ItemBase>());

The answer to the other question works for LINQ to Objects, but not necessarily for LINQ to Entities or LINQ to SQL.

Alternatively, you can convert to LINQ to Objects by calling AsEnumerable:

IQueryable<ItemBase> folderItems = contractItems
        .AsEnumerable()
        .Concat<ItemBase>(changeOrderItems);

However, take care in LINQ to Objects; Concat would work without any overhead (iterating through both collections from the database), but Union would pull one of the collections entirely from the database and then iterate through the other.

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