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

前端 未结 1 1421
小蘑菇
小蘑菇 2020-12-11 15:25

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<         


        
相关标签:
1条回答
  • 2020-12-11 16:06

    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.

    0 讨论(0)
提交回复
热议问题