我正在尝试完全外连接两个列表(单独的类),我必须这样做的原因是因为我需要来自我的系统的所有订单,以及来自另一个系统的订单。有些订单在订单号上匹配,有些订单没有。但我还是想在网格中显示所有订单。
这两个界面看起来像这样
interface IOrderInternal
{
int ID { get; } // My systems inernal ID
string NO_Order { get; } // My external ID
DateTime? OrderDate { get; }
}
interface IOrderExternal
{
int ID { get; } // External systems internal ID
string ProjectNumber{ get; }
}
这两个接口的连接最终应该是
interface IOrderInternal
{
int ID_IN { get; set; }
int ID_EX { get; set; }
string ProjectNumber{ get; set; }
DateTime OrderDate { get; set; }
}
因此,根据NO_Order = ProjectNumber
,在一个应该完全外连接它们的函数中传入两个列表 IList<IOrderInternal> INOrders
IList<IOrderExternal> EXOrders
var leftJoin = from exorder in EXOrders
join inorder in INOrders
on exorder.ProjectNumber equals inorder.NO_Order
into temp
from inorder in temp
select new Order
{
ID_IN = inorder == null ? default(int) : inorder.ID,
ID_EX = exorder.ID,
ProjectNumber = inorder == null ? default(string) : inorder.NO_Order
OrderDate = inorder == null ? default(DateTime) : inorder.OrderDate
};
var rightJoin = from inorderin INOrders
join exorderin EXOrders
on inorder.NO_Order equals exorder.ProjectNumber
into temp
from exorder in temp
select new Order
{
ID_IN = inorder.ID,
ID_EX = exorder == null? default(int) : exorder.ID,
ProjectNumber = inorder.NO_Order
OrderDate = inorder.OrderDate
};
var joinedList = leftJoin.Union(rightJoin);
当我加入列表时,我只得到内部联接的结果。但我需要知道所有订单。
感谢任何帮助:)
答案 0 :(得分:0)
如果我理解正确,你想在任何一个方向进行外连接,然后将结果连接在一起?这就是我在linq中留下连接的方式:
IList<IOrderInternal> INOrders
IList<IOrderExternal> EXOrders
var leftJoin = from exorder in EXOrders
from inorder in INOrders.Where(x => exorder.ProjectNumber == x.NO_Order).DefaultIfEmpty()
select new Order
{
ID_IN = inorder == null ? default(int) : inorder.ID,
ID_EX = exorder.ID,
ProjectNumber = inorder == null ? default(string) : inorder.NO_Order
OrderDate = inorder == null ? default(DateTime) : inorder.OrderDate
};
var rightJoin = from inorderin INOrders
from exorderin EXOrders.Where(x => inorder.NO_Order == x.ProjectNumber).DefaultIfEmpty()
select new Order
{
ID_IN = inorder.ID,
ID_EX = exorder == null? default(int) : exorder.ID,
ProjectNumber = inorder.NO_Order
OrderDate = inorder.OrderDate
};
var joinedList = leftJoin.Union(rightJoin);
我喜欢这种方式,因为它将左连接保持在一行,但如果您想继续使用语法,我认为您只需在每个查询中将temp
更改为temp.DefaultIfEmpty()
让它发挥作用。