1

I have an Orders table and an Assignments table which I join together using LINQ to Entities. Each order has a product and a quantity. Each order has a number of assignments up to the quantity. I want to output the following:

Orders:

ID | OrderCode | Quantity | Other Columns...
1  | 30000-1   | 3        | ...
2  | 41000-7   | 2        | ...

Assignments:

OrderID | Assignment | Other Columns...
1       | 4526       | ...
2       | 2661       | ...
2       | 5412       | ...

I want to output a table like:

OrderCode | Assignment
30000-1   | 4526
30000-1   | 
30000-1   |
41000-7   | 2661
41000-7   | 5412

Any advice would be welcome!

4

1 回答 1

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
于 2013-07-08T20:40:37.407 回答