2. LINQとは
データ(オブジェクト)の集合から簡単な
記述で『必要なオブジェクト』の『必要な
メンバ』を『必要とする順序』で取り出せ
るようにした強力なシンタックスシュガー
• 開発者は抽出条件、抽出するメンバ、抽出順序にのみ
関心を払えばよい
• 取り出すデータの型を用意したり、繰り返し文を書い
たりする必要はない
var query = from x in データの集合
where 抽出条件
orderby 抽出順序のキー項目
select 抽出するメンバ ;
3. 対象となるデータ
配列、LIST<T>(LINQ to Object)
• 独自に定義したオブジェクトや組み込みオブジェクト
の集合
XMLファイル(LINQ to XML)
• XElementオブジェクトのツリー
データベース(LINQ to SQL)
• DataContext経由で取り出すTableオブジェクト
• 当初対応するのはSQL Serverのみ
Entity Data Model(LINQ to Entities)
• Entity Frameworkによって生成されるオブジェクト
• Entity Frameworkは.NET Framework 3.5の最初のリリース
には含まれない予定
4. START - Ver3.5
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
namespace VSUGSAMPLE
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo(@"C:UsersonoDesktopLINQVideo");
List<FileInfo> files = new List<FileInfo>(di.GetFiles());
var query = from f in files
where f.Length > 10 * 1024 * 1024 && f.Length < 15 * 1024 * 1024
select new { f.Name, f.Length };
foreach (var file in query)
Console.WriteLine("{0}:{1}", file.Name, file.Length);
}
}
}
8. LINQ to XML
XMLを意識しないプログラムが可能
XML形式の変換も可能
XElement People = XElement.Parse(
@"<People>
<Person>
<Name>オサダ トシヒロ</Name>
<Gender>1</Gender>
<Age>32</Age>
</Person>
</People>");
var query = from p in People.Descendants("Person")
where (int)p.Element("Gender") == 1 && (int)p.Element("Age") >= 20
orderby (int)p.Element("Age")
select p;
9. LINQ to SQL
データベースと連携するクラスはウィザード
で生成
生成されるT-SQLはパラメータを使用
追加/更新/削除は自動的にトランザクショ
ン化
パーシャルメソッドを使用してビジネスルー
ルの追加が可能
LINQTESTDataContext dtc = new LINQTESTDataContext();
var query = from p in dtc.People
where p.Gender == 1 && p.Age >= 20
orderby p.Age
select p;