4. • C# や VB で SQL みたいな書き方ができる
• let、join、group、orderby など一通りのこ
とはできる
クエリー式
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. すべては 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
コレクション初期化子
オブジェクト初期化子
拡張メソッド
ラムダ式
匿名クラス
8. すべては 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
コレクション初期化子
オブジェクト初期化子
拡張メソッド
ラムダ式
匿名クラス
9. • 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);
10. • 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;
}
}
}
11. • 要するに for や foreach になります
↑
ちょっと乱暴
LINQ to Objects (3)
12. • XElement 族
LINQ to XML (1)
var xml =
new XElement("People",
new XElement("Person",
new XElement(“Name”, “太郎"),
new XElement("Age", 15)
),
new XElement("Person",
new XElement(“Name”, “花子"),
new XElement("Age", 14)
)
);
13. LINQ to XML (2)
var q = xml.Descendants("Person")
.Where(x => (int)x.Element("Age") <= 15);
var q = xml.Descendants("Person")
.Where(x =>
((int?)x.Element("Age") ?? int.MaxValue) <= 15);
xml.Descendants("Person").Max(x =>
(int?)x.Element("Age"))
14. • VB は変態すぎてちょっと、、、
LINQ to XML (3)
Dim xml = _
<People>
<Person>
<Name>太郎</Name>
<Age>15</Age>
</Person>
<Person>
<Name>花子</Name>
<Age>14</Age>
</Person>
</People>
15. • VB は変態すぎてちょっと、、、
LINQ to XML (4)
Dim q = From x In xml...<Person>
Where x.<Age>.Value <= 15
Order By x.<Age>.Value
Select x.<Name>
16. • 見た目は LINQ to Objects とほぼ同じ
LINQ to SQL (1)
var db = new DataClasses1DataContext();
var q = from x in db.People
where x.Age <= 15
select x.Name;
var db = new DataClasses1DataContext();
var q = db.People
.Where(x => x.Age <= 15)
.Select(x => x.Name);
17. • テーブルとかは 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);