本逐步解說示範如何使用 Visual Basic 語言功能來撰寫 Language-Integrated Query (LINQ) 查詢運算式。 本逐步解說示範如何在 Student 物件清單上建立查詢、如何執行查詢,以及如何修改查詢。 查詢包含數個功能,包括物件初始化表達式、本機類型推斷和匿名類型。
完成這個逐步解說之後,您就可以開始使用您感興趣的特定 LINQ 提供者的範例和文件。 LINQ 提供者包括LINQ to SQL、LINQ to DataSet 和LINQ to XML。
建立專案
建立主控台應用程式專案
啟動 Visual Studio。
在 [檔案] 功能表上,指向 [開新檔案] ,然後按一下 [專案] 。
在 [ 已安裝的範本 ] 清單中,按兩下 [Visual Basic]。
在專案類型清單中,按兩下 [ 主控台應用程式]。 在 [ 名稱] 方塊中,輸入專案的名稱,然後按兩下 [ 確定]。
專案已建立。 根據預設,它包含對 System.Core.dll的參考。 此外,[參考頁面,項目設計工具(Visual Basic)] 上的 [匯入的命名空間] 清單也包含 命名空間。
在 [專案設計工具 (Visual Basic) 的 [編譯] 頁面] 上,確保 [選項推斷] 設定為 [開啟]。
新增 In-Memory 數據源
本逐步解說中查詢的數據源是 物件清單 Student 。 每個 Student 物件都包含學生主體中的名字、姓氏、班級年份和學術排名。
若要新增資料來源
Student定義類別,並建立 類別的實例清單。
將新學生新增至學生清單
- 遵循 方法中的
getStudents模式,將 類別的另一個實例Student新增至清單。 將學生加入將使您了解物件初始化器。 如需詳細資訊,請參閱 物件初始化表達式:具名和匿名類型。
建立查詢
執行時,本節中新增的查詢會產生一份學生清單,其學術排名將他們放在前十名。 因為每次查詢都會選取完整的 Student 物件,所以查詢結果的類型為 IEnumerable(Of Student)。 不過,查詢類型通常不會在查詢定義中指定。 相反地,編譯程式會使用本機類型推斷來判斷類型。 如需詳細資訊,請參閱 區域型別推斷。 查詢的範圍變數 currentStudent,可作為來源中每個實例的參考,Student提供 中每個students物件的students屬性存取權。
若要建立簡單的查詢
在專案的方法
Main中,尋找標示如下的位置:' ****Paste query and query execution code from the walkthrough, ' ****or any code of your own, here in Main.複製下列程式代碼並貼入其中。
Dim studentQuery = From currentStudent In students Where currentStudent.Rank <= 10 Select currentStudent將滑鼠指標停留在程式碼中的
studentQuery以確認編譯器指派的類型為IEnumerable(Of Student)。
執行查詢
變數 studentQuery 包含查詢的定義,而不是執行查詢的結果。 查詢通常執行的一般機制是 For Each 迴圈。 傳回序列中的每個項目都會透過迴圈反覆運算變數來存取。 如需查詢執行的詳細資訊,請參閱 撰寫您的第一個 LINQ 查詢。
執行查詢
在專案中的查詢下方新增下列
For Each迴圈。For Each studentRecord In studentQuery Console.WriteLine(studentRecord.Last & ", " & studentRecord.First) Next將滑鼠指標放在迴圈控件變數
studentRecord上方,以查看其數據類型。studentRecord的型別被推斷為Student,因為studentQuery傳回的是Student實例的集合。按 CTRL+F5 建置並執行應用程式。 記下主控台視窗中的結果。
修改查詢
如果查詢結果是以指定的順序進行掃描,會比較容易。 您可以根據任何可用的欄位來排序傳回的序列。
排序結果
請在
Order By語句和Where語句之間加入下列Select子句。 子Order By句會根據每個學生的姓氏,依字母順序從 A 到 Z 排序結果。Order By currentStudent.Last Ascending若要依姓氏和名字排序,請將這兩個字段新增至查詢:
Order By currentStudent.Last Ascending, currentStudent.First Ascending您也可以指定
Descending從 Z 到 A 的順序。按 CTRL+F5 建置並執行應用程式。 記下主控台視窗中的結果。
介紹地方標識碼
新增本節中的程式碼,以在查詢表達式中加入本地識別碼。 本地標識符會保存中繼結果。 在下列範例中,
name是保存學生名字和姓氏串連的標識碼。 區域識別碼可出於方便使用,或可藉由儲存原本會多次計算的表達式結果來增強效能。Dim studentQuery2 = From currentStudent In students Let name = currentStudent.Last & ", " & currentStudent.First Where currentStudent.Year = "Senior" And currentStudent.Rank <= 10 Order By name Ascending Select currentStudent ' If you see too many results, comment out the previous ' For Each loop. For Each studentRecord In studentQuery2 Console.WriteLine(studentRecord.Last & ", " & studentRecord.First) Next按 CTRL+F5 建置並執行應用程式。 記下主控台視窗中的結果。
若要在 Select 子句中投影一個字段
在這一節中新增查詢和
For Each迴圈,以創建一個查詢,產生出序列,其元素與來源元素不同。 在下列範例中,來源是 物件的集合Student,但只會傳回每個物件的一個成員:姓氏為 Garcia 的學生名字。 因為currentStudent.First是字串,因此 所studentQuery3傳回之序列的數據類型為IEnumerable(Of String),是字串序列。 如同先前的範例,studentQuery3的資料類型會由編譯器通過局部類型推斷來決定。Dim studentQuery3 = From currentStudent In students Where currentStudent.Last = "Garcia" Select currentStudent.First ' If you see too many results, comment out the previous ' For Each loops. For Each studentRecord In studentQuery3 Console.WriteLine(studentRecord) Next將滑鼠指標移到您的程式碼中的
studentQuery3上,以驗證指派的類型是否為IEnumerable(Of String)。按 CTRL+F5 建置並執行應用程式。 記下主控台視窗中的結果。
在 Select 子句中建立匿名類型
新增本節中的程序代碼,以查看如何在查詢中使用匿名類型。 當您想要從數據源傳回數個字段,而不是完整記錄(先前範例中的記錄)或單一欄位(
currentStudentFirst在上一節中)時,您可以在查詢中使用它們。 您指定Select子句中的欄位,編譯器會使用這些欄位作為其屬性來建立匿名型別,而不是定義包含結果中欄位的新具名型別。 如需詳細資訊,請參閱 匿名型別。下列範例會建立查詢,以學術排名的順序傳回其學術排名介於 1 到 10 之間的老年人名稱和排名。 在此範例中,必須推斷 的
studentQuery4型別,因為Select子句會傳回匿名類型的實例,而匿名型別沒有可使用的名稱。Dim studentQuery4 = From currentStudent In students Where currentStudent.Year = "Senior" And currentStudent.Rank <= 10 Order By currentStudent.Rank Ascending Select currentStudent.First, currentStudent.Last, currentStudent.Rank ' If you see too many results, comment out the previous ' For Each loops. For Each studentRecord In studentQuery4 Console.WriteLine(studentRecord.Last & ", " & studentRecord.First & ": " & studentRecord.Rank) Next按 CTRL+F5 建置並執行應用程式。 記下主控台視窗中的結果。
其他範例
現在您已瞭解基本概念,以下是說明LINQ查詢彈性和功能的其他範例清單。 每個範例前面都會有其用途的簡短描述。 將滑鼠指標放在每個查詢的查詢結果變數上方,以查看推斷的類型。 使用For Each迴圈來產生結果。
' Find all students who are seniors.
Dim q1 = From currentStudent In students
Where currentStudent.Year = "Senior"
Select currentStudent
' Write a For Each loop to execute the query.
For Each q In q1
Console.WriteLine(q.First & " " & q.Last)
Next
' Find all students with a first name beginning with "C".
Dim q2 = From currentStudent In students
Where currentStudent.First.StartsWith("C")
Select currentStudent
' Find all top ranked seniors (rank < 40).
Dim q3 = From currentStudent In students
Where currentStudent.Rank < 40 And currentStudent.Year = "Senior"
Select currentStudent
' Find all seniors with a lower rank than a student who
' is not a senior.
Dim q4 = From student1 In students, student2 In students
Where student1.Year = "Senior" And student2.Year <> "Senior" And
student1.Rank > student2.Rank
Select student1
Distinct
' Retrieve the full names of all students, sorted by last name.
Dim q5 = From currentStudent In students
Order By currentStudent.Last
Select Name = currentStudent.First & " " & currentStudent.Last
' Determine how many students are ranked in the top 20.
Dim q6 = Aggregate currentStudent In students
Where currentStudent.Rank <= 20
Into Count()
' Count the number of different last names in the group of students.
Dim q7 = Aggregate currentStudent In students
Select currentStudent.Last
Distinct
Into Count()
' Create a list box to show the last names of students.
Dim lb As New System.Windows.Forms.ListBox
Dim q8 = From currentStudent In students
Order By currentStudent.Last
Select currentStudent.Last Distinct
For Each nextName As String In q8
lb.Items.Add(nextName)
Next
' Find every process that has a lowercase "h", "l", or "d" in its name.
Dim letters() As String = {"h", "l", "d"}
Dim q9 = From proc In System.Diagnostics.Process.GetProcesses,
letter In letters
Where proc.ProcessName.Contains(letter)
Select proc
For Each proc In q9
Console.WriteLine(proc.ProcessName & ", " & proc.WorkingSet64)
Next
其他資訊
熟悉使用查詢的基本概念之後,您就可以閱讀您感興趣的特定 LINQ 提供者類型的檔和範例: