Archive for the ‘C#’ Category

色々読んではいたけど、触ってなかったので触ってみました。
お試しコード紹介。

同じ名前の人を引っ張る LINQ です。

C#:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace ConsoleApplication
  6. {
  7.     class Student
  8.     {
  9.         public int id { get; set; }
  10.         public string name { get; set; }
  11.  
  12.         public Student(int id, string name)
  13.         {
  14.             this.id = id;
  15.             this.name = name;
  16.         }
  17.  
  18.         public void output()
  19.         {
  20.             Console.WriteLine("id:{0} name:{1}", id, name);
  21.         }
  22.     };
  23.  
  24.     class Program
  25.     {
  26.         static void Main(string[] args)
  27.         {
  28.             Student[] classA = {
  29.                 new Student(0, "sova"),
  30.                 new Student(1, "nana"),
  31.                 new Student(2, "j2"),
  32.                 new Student(3, "taro"),
  33.                 new Student(4, "chu"),
  34.             };
  35.             Student[] classB = {
  36.                 new Student(0, "tof"),
  37.                 new Student(1, "taro"),
  38.                 new Student(2, "dode"),
  39.                 new Student(3, "doru"),
  40.                 new Student(4, "kmb"),
  41.             };
  42.             IEnumerable<student> query = from a in classA
  43.                                          join b in classB on a.name equals b.name
  44.                                          select a;
  45.             foreach (Student item in query)
  46.             {
  47.                 item.output();
  48.             }
  49.         }
  50.     }
  51. }

from で複数のテーブル選択したいときは

from h in hoge
from f in fuga

のようにすれば良いみたい。

from hoge, fuga

のように書きたくなるけど、これはNG。

触った感想としては insert, update, delete, drop といった直接的な操作が無い。
inner join とか left join とかの区別はなくて、join だけある感じ。
LINQ は select でデータを取り出して、データ操作自体は LINQ の外でやってねー、という方針みたいですね。
構文は慣れると全然簡単だね、便利だわ〜。

# SQL 書いてると、構文が逆だから混乱するかと思ったけどそうでもない。