ページ

2011年4月4日月曜日

◆LINQで射影(Select)

抽出(Where)の所でもSelectは使っていたのだが、改めてSelectのサンプル。

Selectとは集合論で言うところの射影の機能。
抽出(Where)と違って元々の型とは違う型になってしまう。
なので、予めSelect後の型を用意したサンプルが以下。

  1. //射影(Select)  
  2. public class MyAuthor  
  3. {  
  4.     public string au_id { getset; }  
  5.     public string au_name { getset; }  
  6.     public string phone { getset; }  
  7.     public string state { getset; }  
  8. }  
  9.   
  10. public void linqSelect(Form1 form)  
  11. {  
  12.     using (PubsDataContext pubs = new PubsDataContext())  
  13.     {  
  14.         IEnumerable<MyAuthor> myAuth = pubs.authors.Select(a => new MyAuthor  
  15.             {  
  16.                 au_id = a.au_id,  
  17.                 au_name = a.au_fname + " " + a.au_lname,  
  18.                 phone = a.phone,  
  19.                 state = a.state  
  20.             });  
  21.         form.dataGridView1.DataSource = myAuth;  
  22.     }  
  23. }  

っで、射影して取って来る度にクラスが必要になるんじゃ面倒だよね・・・。LINQって使えないな。
っとならないようにLINQと共に導入されたのが自動型推定の(var)と匿名データ型。
このvarはVBのvariant型とは違い何でも入る型と言う訳ではなく、コンパイラーが自動的に型を推定して決めてくれる。
var  hoge = “abc”;
なら、明らかにstringだよねって感じ。
また、今回みたいな射影(Select)の様な時は、newの後ろのクラス名を省略するとコンパイラーが適当に任意のクラス(匿名データ型)を作って割り当ててくれる。


なので上記のサンプルはわざわざMyクラスを作らなくても以下のように書くことができる。


  1. //射影(Select)  
  2. //public class MyAuthor  
  3. //{  
  4. //    public string au_id { get; set; }  
  5. //    public string au_name { get; set; }  
  6. //    public string phone { get; set; }  
  7. //    public string state { get; set; }  
  8. //}  
  9.   
  10. public void linqSelect(Form1 form)  
  11. {  
  12.     using (PubsDataContext pubs = new PubsDataContext())  
  13.     {  
  14.         //IEnumerable<MyAuthor> myAuth = pubs.authors.Select(a => new MyAuthor  
  15.         var myAuth = pubs.authors.Select(a => new   
  16.         {  
  17.                 a.au_id,  
  18.                 au_name = a.au_fname + " " + a.au_lname,  
  19.                 a.phone,  
  20.                 a.state  
  21.             });  
  22.         form.dataGridView1.DataSource = myAuth;  
  23.     }  
  24. }  

埋め込みクエリー方式ではこうなる。


  1. public void linqSelect(Form1 form)  
  2. {  
  3.     using (PubsDataContext pubs = new PubsDataContext())  
  4.     {  
  5.         var myAuth = from a in pubs.authors  
  6.                         select new   
  7.                         {  
  8.                             a.au_id,  
  9.                             au_name = a.au_fname + " " + a.au_lname,  
  10.                             a.phone,  
  11.                             a.state  
  12.                         };  
  13.                         form.dataGridView1.DataSource = myAuth;  
  14.         Console.Beep();  
  15.     }  
  16. }  

0 件のコメント:

コメントを投稿

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