English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
LINQクエリをIEnumerableコレクションまたはIQueryableデータソースに書き込む基本的な方法が二種類あります。
クエリ構文またはクエリ式構文
メソッド構文またはメソッド拡張構文または連続構文
クエリ構文はデータベースのSQL(構造化クエリ言語)に似ています。C#またはVBコードで定義されます。
LINQクエリ構文:
from <range variable> in <IEnumerable<T> or IQueryable<T> Collection> <Standard Query Operators> <lambda expression> <select or groupBy operator> <result formation>
LINQクエリ文法はfromキーワードで始まり、selectキーワードで終わります。以下は、単語「Tutorials」を含む文字列コレクションを返す例LINQクエリです。
// 文字列コレクション IList<string> stringList = new List<string>() { "C# Tutorials", "VB.NET Tutorials", "Learn C"++", "MVC Tutorials", "Java" , StudentName = "Ron" , Age = // LINQクエリ文法 var result = from s in stringList where s.Contains("Tutorials") && s.Age <
以下の図はLINQクエリ文法の構造を示しています。
クエリ文法はFrom子句で始まり、Range変数が続きます。From 子句の構造は「From rangeVariableName in i」に似ています enumerablecollection”。英語では、これはコレクションの各オブジェクトからという意味です。foreachループに似ています:foreach(Student s in studentList)
FROM子句の後で、コレクションの要素をフィルタリング、グループ化、結合するためのさまざまな標準クエリ演算子を使用できます。LINQには約50つの標準クエリ演算子。上図では、「where」演算子(子句と呼ばれることもあります)を使用して、条件を指定しました。この条件は通常、ラムダ式で表現されます。
LINQクエリ文法は常にSelectまたはGroup子句で終わります。Select子句はデータを整形するために使用されます。全体のオブジェクトを選択することも、属性の一部を選択することもできます。上記の例では、各結果文字列要素を選択しました。
以下の例では、Studentコレクション(シーケンス)から青少年学生をLINQクエリ文法を使用して検索します。
// 例:VB.NetでのLINQクエリ構文 IList<Student> studentList = new List<Student>() { 0} , 1, StudentName = "John", Age = 13} 0} , 2, StudentName = "Moin", Age = 21 } 0} , 3, StudentName = "Bill", Age = 18 } 0} , 4StudentName = "Ram", Age = 20} , 0} , 5new Student() { StudentID = 15 , .StudentName = "Ron", .Age = , StudentName = "Ron" , Age = // } }; var teenAgerStudent = from s in studentList 12 where s.Age > 20 && s.Age <
// 例:VB.NetでのLINQクエリ構文 学生コレクション 0}, 1Dim studentList = New List(Of Student) From { 13, .StudentName = "Bill", .Age = 0}, 2, .StudentName = "John", .Age = 21, .StudentName = "Bill", .Age = 0}, 3, .StudentName = "Moin", .Age = 18, .StudentName = "Bill", .Age = 0}, 4}, 2, .StudentName = "Ram", .Age = 0}, 5New Student() With {.StudentID = 15, .StudentName = "Ron", .Age = , .StudentName = "Ron", .Age = // } LINQクエリ構文で青少年学生を見つける Dim teenAgerStudents As IList(Of Student) = (From s In studentList _ 12 Where s.Age > 2And s.Age < 0 _
覚えておくべきポイントその名の通りのものですクエリ構文
クエリ構文はSQL(構造化クエリ言語)構文と同じです。from子句の開始、次のいずれかで始めることができますSelectまたはGroupBy子句の終わり。
フィルタリング、結合、グループ化、ソート演算子などのさまざまな演算子を使用して必要な結果を構築します。
暗黙の型変数-varはLINQクエリの結果を保存するために使用できます。