简体   繁体   中英

Linq Full Outer Join Error

I am connected to the Adventure Works 2012 database using Linqpad as shown below:

在此处输入图片说明

I am trying to write a full outer join. My research tells me it should look like this (as shown in the screenshot):

var LeftOuterJoin =  from p in Products
join pv in ProductVendors on p.ProductID equals pv.ProductID into ppv
from pv in ppv.DefaultIfEmpty()
select new {ProductName = p.Name};

var RightOuterJoin =  from v in Vendors
join pv in ProductVendors on v.BusinessEntityID equals pv.BusinessEntityID into ppv
from pv in ppv.DefaultIfEmpty()
select new {VendorName = v.Name};

LeftOuterJoin.Union(RightOuterJoin);

However, the error in the screenshot (see screenshot) is:

'System.Linq.IQueryable<AnonymousType#1>' does not contain a definition for 'Union' and the best extension method overload 'System.Linq.ParallelEnumerable.Union<TSource>(System.Linq.ParallelQuery<TSource>, System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments

Instance argument: cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.ParallelQuery<AnonymousType#2>'

What is the problem?

As i can see , there is type issue , both anonymous type have different property , so that will be causing the issue for using Union . you can create a common type with same property and use it. or have both property and use according to query Like:

var LeftOuterJoin =  from p in Products
join pv in ProductVendors on p.ProductID equals pv.ProductID into ppv
from pv in ppv.DefaultIfEmpty()
select new {VendorName = "",
            ProductName = p.Name,};

var RightOuterJoin =  from v in Vendors
join pv in ProductVendors on v.BusinessEntityID equals pv.BusinessEntityID into ppv
from pv in ppv.DefaultIfEmpty()
select new {VendorName = v.Name,
            ProductName = "",};

var result = LeftOuterJoin.Union(RightOuterJoin).ToList(); // force execution to get results.

use this if you are using LinqPad

var result = LeftOuterJoin.Union(RightOuterJoin)
result .Dump();

This will work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM