4. LINQ (2)
• コレクションの検索
– 配列や List<T> など
LINQ to Objects
• データベースの検索
– DataContext
LINQ to SQL
5. クエリー式 (1)
• C# や VB で SQL みたいな書き方ができ
る
var array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var q = from x in array
where x % 2 == 0
select x;
Dim array() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim q = From x In array
Where x Mod 2 = 0
Select x
7. クエリー式 (3)
• VB の Skip、Take
Dim q = From x In array
Skip 3
Take 2
Select x
• VB の Aggregate
Dim total = Aggregate x In array
Where x Mod 2 = 0
Into Sum(x)
10. LINQ のための言語サポート(2)
コレクション初期化子
var
オブジェクト初期化子
var people = new[]
{
new Person() { Name = “太郎", Age = 14, },
new Person() { Name = “花子", Age = 17, },
};
var q = people
.Where(x => x.Age <= 15)
.Select(x => new { x.Name });
匿名クラス
拡張メソッド
ラムダ式
11. LINQ のための言語サポート(3)
コレクション初期化子
var
オブジェクト初期化子
Dim people() =
{
New Person() With {.Name = “太郎", .Age = 15},
New Person() With {.Name = “花子", .Age = 14}
}
Dim q = people.
Where(Function(x) x.Age <= 15).
Select(Function(x) New With {x.Name})
匿名クラス
拡張メソッド
ラムダ式
12. LINQ to Objects (1)
• IEnumerable
– 配列やコレクションは IEnumerable を実装し
ている
• だから
– System.Linq.Enumerable
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate);
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, int, bool> predicate);
14. LINQ to SQL (1)
• 見た目は LINQ to Objects とほぼ同じ
var db = new NorthwindDataContext();
var q = from c in db.Customers
where c.Country == “USA”
select c.ContactName;
var db = new NorthwindDataContext();
var q = db.Customers
.Where(c => c.Country == “USA”)
.Select(c => c.ContactName);
15. LINQ to SQL (2)
• テーブルとかは IQueryable
• だから
– System.Linq.Queryable
public static IQueryable<TSource> Where<TSource>(
this IQueryable<TSource> source,
Expression<Func<TSource, bool>> predicate);
public static IQueryable<TSource> Where<TSource>(
this IQueryable<TSource> source,
Expression<Func<TSource, int, bool>> predicate);
17. LINQ to XML (1)
• もう一つの XML API
– W3C の XmlDocument とかとは別
• XDocument、XElement、XAttribute
– System.Xml.Linq 名前空間
18. XDocument 属の便利なところ (1)
• コンストラクタが便利
var xml = new XDocument(
new XElement("AddressBook",
new XElement("Person", new XAttribute("Id", 100),
new XElement("Name", "太郎"),
new XElement("Age", 20)),
new XElement("Person", new XAttribute("Id", 101),
new XElement("Name", "花子"),
new XElement("Age", 25))
)
);
19. XDocument 属の便利なところ (2)
• LINQ で使えるのが便利
var q = from x in xml.Elements("AddressBook")
.Elements("Person")
where x.Attribute("Id").Value == "100"
select x;
var q = xml.Elements("AddressBook")
.Elements("Person")
.Where(x => x.Attribute("Id").Value == "100");
20. XDocument 属の便利なところ (3)
• 明示的な型変換が便利
var n = xml.Elements("AddressBook")
.Elements("Person")
.Max(x => (int)x.Element("Age"));
• Nullable への明示的な型変換が便利
var n = xml.Elements("AddressBook")
.Elements("Person")
.Max(x => (int?)x.Element("Age") ?? -1);