Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to combine (union or concat) two lists/collection into one. The two lists have a common base class. e.g. I've tried this:

        IQueryable<ContractItem> contractItems = myRepository.RetrieveContractItems();
        IQueryable<ChangeOrderItem> changeOrderItems = myRepository.RetrieveChangeOrderItems();

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

But am getting the LINQ error DbUnionAllExpression requires arguments with compatible collection ResultTypes.

Anybody know how to do this properly? The only thing I could google was another StackOverflow question: LINQ Union objects with same Base Class

Thanks.

like image 617
Raymond Avatar asked Jul 07 '11 17:07

Raymond


1 Answers

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.

like image 74
Stephen Cleary Avatar answered Oct 23 '22 22:10

Stephen Cleary