抽出(Where)の所でもSelectは使っていたのだが、改めてSelectのサンプル。
Selectとは集合論で言うところの射影の機能。
抽出(Where)と違って元々の型とは違う型になってしまう。
なので、予めSelect後の型を用意したサンプルが以下。
- //射影(Select)
- public class MyAuthor
- {
- public string au_id { get; set; }
- public string au_name { get; set; }
- public string phone { get; set; }
- public string state { get; set; }
- }
- public void linqSelect(Form1 form)
- {
- using (PubsDataContext pubs = new PubsDataContext())
- {
- IEnumerable<MyAuthor> myAuth = pubs.authors.Select(a => new MyAuthor
- {
- au_id = a.au_id,
- au_name = a.au_fname + " " + a.au_lname,
- phone = a.phone,
- state = a.state
- });
- form.dataGridView1.DataSource = myAuth;
- }
- }
っで、射影して取って来る度にクラスが必要になるんじゃ面倒だよね・・・。LINQって使えないな。
っとならないようにLINQと共に導入されたのが自動型推定の(var)と匿名データ型。
このvarはVBのvariant型とは違い何でも入る型と言う訳ではなく、コンパイラーが自動的に型を推定して決めてくれる。
var hoge = “abc”;
なら、明らかにstringだよねって感じ。
また、今回みたいな射影(Select)の様な時は、newの後ろのクラス名を省略するとコンパイラーが適当に任意のクラス(匿名データ型)を作って割り当ててくれる。
なので上記のサンプルはわざわざMyクラスを作らなくても以下のように書くことができる。
- //射影(Select)
- //public class MyAuthor
- //{
- // public string au_id { get; set; }
- // public string au_name { get; set; }
- // public string phone { get; set; }
- // public string state { get; set; }
- //}
- public void linqSelect(Form1 form)
- {
- using (PubsDataContext pubs = new PubsDataContext())
- {
- //IEnumerable<MyAuthor> myAuth = pubs.authors.Select(a => new MyAuthor
- var myAuth = pubs.authors.Select(a => new
- {
- a.au_id,
- au_name = a.au_fname + " " + a.au_lname,
- a.phone,
- a.state
- });
- form.dataGridView1.DataSource = myAuth;
- }
- }
埋め込みクエリー方式ではこうなる。
- public void linqSelect(Form1 form)
- {
- using (PubsDataContext pubs = new PubsDataContext())
- {
- var myAuth = from a in pubs.authors
- select new
- {
- a.au_id,
- au_name = a.au_fname + " " + a.au_lname,
- a.phone,
- a.state
- };
- form.dataGridView1.DataSource = myAuth;
- Console.Beep();
- }
- }
0 件のコメント:
コメントを投稿