我有一个Orders表和一个Assignments表,我使用LINQ to Entities连接在一起。每个订单都有产品和数量。每个订单都有多个分配数量。我想输出以下内容:
订单:
ID | OrderCode | Quantity | Other Columns...
1 | 30000-1 | 3 | ...
2 | 41000-7 | 2 | ...
作业:
OrderID | Assignment | Other Columns...
1 | 4526 | ...
2 | 2661 | ...
2 | 5412 | ...
我想输出一个表格,如:
OrderCode | Assignment
30000-1 | 4526
30000-1 |
30000-1 |
41000-7 | 2661
41000-7 | 5412
欢迎任何建议!
答案 0 :(得分:0)
我会将任务分成三部分。
首先,我使用LINQ to Entities获取完整的订单集合,每个订单都有相应的分配集合:
var a = (from o in orders
join a in assignments on s.Id equals a.OrderId into oa
//Notice that I use oa.DefaultIfEmpty(). This essentially the way to do a
//LEFT JOIN in LINQ. You'll want to do a LEFT JOIN if you don't
//want to exclude order codes that have no assignments
select new { o.OrderCode, o.Quantity, Assignments = oa.DefaultIfEmpty() })
.ToList();
a
会为您的示例返回以下内容:
OrderCode | Assignment
30000-1 | 4526
41000-7 | 2661
41000-7 | 5412
然后我会添加“缺失”行
var b = a.SelectMany(o =>
{
var numOrdersInList = o.Count(o2 => o2.OrderCode == o.OrderCode);
return Enumerable.Range(0, o.Quantity - numOrdersInList)
.Select(i => new
{
o.OrderCode,
Assignment = Enumerable.Empty<Assignment>()
});
});
b
会为您的示例返回以下内容:
OrderCode | Assignment
30000-1 |
30000-1 |
然后我会把这两个枚举点连接起来。
var c = a.Select(o => new { o.OrderCode, o.Assignment })
.Concat(b);
最后,连接应该返回您对示例的期望:
OrderCode | Assignment
30000-1 | 4526
30000-1 |
30000-1 |
41000-7 | 2661
41000-7 | 5412