NorthwindのOrderとOrder_Detailのように1対多で多を集計していく処理。
MTG Blog: ◆LINQで明細集計処理で行ったのと同じ処理をリレーションが張られていないものとしてGroupJoinを使って集計してみる。
自分でJoinしなければいけない分やはり若干面倒な処理となる。
- //グループ化結合処理(GroupJoin)
- public void linqGroupJoin(Form1 form)
- {
- using (NorthWindDataContext nwnd = new NorthWindDataContext())
- {
- var sumPrice = nwnd.Order.GroupJoin(nwnd.Order_Details,
- o => o.OrderID, od => od.OrderID,
- (o, g) => new
- {
- o.OrderID,
- o.CustomerID,
- price = g.Sum(od => od.Quantity * od.UnitPrice)
- });
- form.dataGridView1.DataSource = sumPrice;
- }
- }
8行目でOrder_Detailをグループ化したコレクションをgで参照するよう指定している。
あとは、リレーションが張られているときと同様にSum拡張メソッドで集計してあげればOKだ。
埋め込みクエリー方式はこちら。
- //グループ化結合処理(GroupJoin)
- public void linqGroupJoin(Form1 form)
- {
- using (NorthWindDataContext nwnd = new NorthWindDataContext())
- {
- var sumPrice = from o in nwnd.Order
- join od in nwnd.Order_Details on o.OrderID equals od.OrderID into g
- select new
- {
- o.OrderID,
- o.CustomerID,
- price = g.Sum(od => od.Quantity * od.UnitPrice)
- };
- form.dataGridView1.DataSource = sumPrice;
- Console.Beep();
- }
- }
グループ化後のOrder_Detailをintoでgに入れている。
0 件のコメント:
コメントを投稿