ページ

2011年4月9日土曜日

◆LINQで複合キーを使った集計処理

複合キーを匿名データ型で指定する以外は通常のグループ集計処理と同じ。
この様な処理ではあまりLINQのメリットは感じられない。(SQLで書いたほうが分かりやすく簡単かも)

  1. //複合キーでのグループ化処理  
  2. public void linqGroupComplex(Form1 form)  
  3. {  
  4.     using (NorthWindDataContext nwnd = new NorthWindDataContext())  
  5.     {  
  6.         nwnd.Log = Console.Out;  
  7.         var customers = nwnd.Customers.GroupBy(c => new {c.Country,c.City})  
  8.                                       .OrderBy(g => g.Key.Country)  
  9.                                       .ThenBy(g => g.Key.City)  
  10.                                       .Select(g => new  
  11.                                       {  
  12.                                           g.Key.Country,  
  13.                                           g.Key.City,  
  14.                                           count = g.Count()  
  15.                                       });  
  16.         form.dataGridView1.DataSource = customers;  
  17.     }  
  18. }  

埋め込みクエリー方式では以下のとおり。


  1. //複合キーでのグループ化処理  
  2. public void linqGroupComplex(Form1 form)  
  3. {  
  4.     using (NorthWindDataContext nwnd = new NorthWindDataContext())  
  5.     {  
  6.         var customers = from c in nwnd.Customers  
  7.                         group c by new{c.Country,c.City} into g  
  8.                         orderby g.Key.Country,g.Key.City  
  9.                         select new  
  10.                         {  
  11.                             g.Key.Country,  
  12.                             g.Key.City,  
  13.                             count = g.Count()  
  14.                         };  
  15.         form.dataGridView1.DataSource = customers;  
  16.         Console.Beep();  
  17.     }  
  18. }  

0 件のコメント:

コメントを投稿

私が最近チェックした記事