4. • コレクションの検索
– 配列や List<T> など
LINQ to Objects
• データベースの検索
– DataContext
LINQ to SQL
LINQ (2)
5. • C# や VB で SQL みたいな書き方ができ
る
クエリー式 (1)
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. • VB の Skip、Take
• VB の Aggregate
クエリー式 (3)
Dim q = From x In array
Skip 3
Take 2
Select x
Dim total = Aggregate x In array
Where x Mod 2 = 0
Into Sum(x)
10. LINQ のための言語サポート(2)
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 });
var
コレクション初期化子
オブジェクト初期化子
拡張メソッド
ラムダ式
匿名クラス
11. LINQ のための言語サポート(3)
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})
var
コレクション初期化子
オブジェクト初期化子
拡張メソッド
ラムダ式
匿名クラス
12. • IEnumerable
– 配列やコレクションは IEnumerable を実装し
ている
• だから
– System.Linq.Enumerable
LINQ to Objects (1)
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);
13. • System.Linq.Enumerable.Where
LINQ to Objects (2)
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
foreach (var item in source)
{
if (predicate(item))
{
yield return item;
}
}
}
15. • 見た目は LINQ to Objects とほぼ同じ
LINQ to SQL (1)
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);
16. • テーブルとかは IQueryable
• だから
– System.Linq.Queryable
LINQ to SQL (2)
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);