1

LINQ to Entities を使用して結合する Orders テーブルと Assignments テーブルがあります。各注文には製品と数量があります。各注文には、数量までの数の割り当てがあります。以下を出力したい。

注文:

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

どんなアドバイスでも大歓迎です!

4

1 に答える 1

0

タスクを 3 つの部分に分割します。

まず、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   |

次に、2 つの列挙型を連結します。

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 に答える