Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL, How to merge multiple IQueryable Lists of different subtype?

Consider the following code

IQueryable<FooBar> fooBarQuery = _fooBar;
IQueryable<FooBaz> fooBazQuery = _fooBaz;
IQueryable<IFoo> mergedQuery = _fooBar.Cast<IFoo>().Concat(_fooBaz.Cast<IFoo>());

The above will merged the _fooBar and _fooBaz. However, the object type in the merged query list will all change to FooBar. If I flip the concat (_fooBaz concat to _fooBar), the object type will change to FooBaz.

I believe, Due to this Subsequent concat on mergedQuery will throw this error: "Types in Union or Concat have members assigned in different order."

Can anybody help me how to merge multiple IQueryable lists of different subtypes?

like image 663
RWendi Avatar asked Mar 19 '14 03:03

RWendi


2 Answers

A solution is to use intermediate objects:

interface IFoo
{
    int PorpertyA { get; }
    int PorpertyB { get; }
    ...
}

class FooImpl : IFoo
{
    public int PorpertyA { get; set; }
    public int PorpertyB { get; set; }
    ...
}

IQueryable<IFoo> mergedQuery =
    fooBarQuery.Select(x => new FooImpl {
        PropertyA = x.PropertyA,
        PropertyB = x.PropertyB
        ...
    })
    .Union(fooBazQuery.Select(x => new FooImpl {
        PropertyA = x.PropertyA,
        PropertyB = x.PropertyB
        ...
    });
like image 165
nlips Avatar answered Nov 14 '22 22:11

nlips


The code you provided itself merge the two IQueryable lists of different subtypes. May be I don't understand the problem statement correctly. I have used the following code.

        List<FooBar> lstFooBar = new List<FooBar>() { new FooBar() { r = 1 } };
        List<FooBaz> lstFooBaz = new List<FooBaz>() { new FooBaz() { z = 2 } };

        IQueryable<FooBar> fooBarQuery = lstFooBar.AsQueryable<FooBar>();
        IQueryable<FooBaz> fooBazQuery = lstFooBaz.AsQueryable<FooBaz>();

        IQueryable<IFoo> mergedQuery = fooBazQuery.Cast<IFoo>  
                                       ().Concat(fooBarQuery.Cast<IFoo>());

Where the classes implementation was as follows:

 interface IFoo
  {
    int A { get; set; }
   }

class FooBar : IFoo
{
    public int r { get; set; }
    public int A { get; set; }
}

class FooBaz : IFoo
{
    public int z { get; set; }
    public int A { get; set; }
}

See in the following attachment the two members of the merged query are of different type , not of same type. If there is any understanding issue then please let me know.

ScreenShot

like image 36
Abhishek Gahlout Avatar answered Nov 14 '22 23:11

Abhishek Gahlout