共用方式為


逐步解說:在 Visual Basic 中撰寫查詢

本逐步解說示範如何使用 Visual Basic 語言功能來撰寫 Language-Integrated Query (LINQ) 查詢運算式。 本逐步解說示範如何在 Student 物件清單上建立查詢、如何執行查詢,以及如何修改查詢。 查詢包含數個功能,包括物件初始化表達式、本機類型推斷和匿名類型。

完成這個逐步解說之後,您就可以開始使用您感興趣的特定 LINQ 提供者的範例和文件。 LINQ 提供者包括LINQ to SQL、LINQ to DataSet 和LINQ to XML。

建立專案

建立主控台應用程式專案

  1. 啟動 Visual Studio。

  2. [檔案] 功能表上,指向 [開新檔案] ,然後按一下 [專案]

  3. 在 [ 已安裝的範本 ] 清單中,按兩下 [Visual Basic]。

  4. 在專案類型清單中,按兩下 [ 主控台應用程式]。 在 [ 名稱] 方塊中,輸入專案的名稱,然後按兩下 [ 確定]。

    專案已建立。 根據預設,它包含對 System.Core.dll的參考。 此外,[參考頁面,項目設計工具(Visual Basic)] 上的 [匯入的命名空間] 清單也包含 命名空間。

  5. 在 [專案設計工具 (Visual Basic) 的 [編譯] 頁面] 上,確保 [選項推斷] 設定為 [開啟]

新增 In-Memory 數據源

本逐步解說中查詢的數據源是 物件清單 Student 。 每個 Student 物件都包含學生主體中的名字、姓氏、班級年份和學術排名。

若要新增資料來源

  • Student定義類別,並建立 類別的實例清單。

    這很重要

    如何Student中提供定義 類別及建立逐步解說範例中使用的清單所需的程序代碼。 您可以從該處複製它,並將它貼到您的專案中。 新的程式代碼會取代您在建立項目時出現的程式代碼。

將新學生新增至學生清單

建立查詢

執行時,本節中新增的查詢會產生一份學生清單,其學術排名將他們放在前十名。 因為每次查詢都會選取完整的 Student 物件,所以查詢結果的類型為 IEnumerable(Of Student)。 不過,查詢類型通常不會在查詢定義中指定。 相反地,編譯程式會使用本機類型推斷來判斷類型。 如需詳細資訊,請參閱 區域型別推斷。 查詢的範圍變數 currentStudent,可作為來源中每個實例的參考,Student提供 中每個students物件的students屬性存取權。

若要建立簡單的查詢

  1. 在專案的方法 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
    
  2. 將滑鼠指標停留在程式碼中的 studentQuery 以確認編譯器指派的類型為 IEnumerable(Of Student)

執行查詢

變數 studentQuery 包含查詢的定義,而不是執行查詢的結果。 查詢通常執行的一般機制是 For Each 迴圈。 傳回序列中的每個項目都會透過迴圈反覆運算變數來存取。 如需查詢執行的詳細資訊,請參閱 撰寫您的第一個 LINQ 查詢

執行查詢

  1. 在專案中的查詢下方新增下列 For Each 迴圈。

    For Each studentRecord In studentQuery
        Console.WriteLine(studentRecord.Last & ", " & studentRecord.First)
    Next
    
  2. 將滑鼠指標放在迴圈控件變數 studentRecord 上方,以查看其數據類型。 studentRecord 的型別被推斷為 Student,因為 studentQuery 傳回的是 Student 實例的集合。

  3. 按 CTRL+F5 建置並執行應用程式。 記下主控台視窗中的結果。

修改查詢

如果查詢結果是以指定的順序進行掃描,會比較容易。 您可以根據任何可用的欄位來排序傳回的序列。

排序結果

  1. 請在Order By 語句和Where 語句之間加入下列Select 子句。 子 Order By 句會根據每個學生的姓氏,依字母順序從 A 到 Z 排序結果。

    Order By currentStudent.Last Ascending
    
  2. 若要依姓氏和名字排序,請將這兩個字段新增至查詢:

    Order By currentStudent.Last Ascending, currentStudent.First Ascending
    

    您也可以指定 Descending 從 Z 到 A 的順序。

  3. 按 CTRL+F5 建置並執行應用程式。 記下主控台視窗中的結果。

介紹地方標識碼

  1. 新增本節中的程式碼,以在查詢表達式中加入本地識別碼。 本地標識符會保存中繼結果。 在下列範例中, 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
    
  2. 按 CTRL+F5 建置並執行應用程式。 記下主控台視窗中的結果。

若要在 Select 子句中投影一個字段

  1. 在這一節中新增查詢和 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
    
  2. 將滑鼠指標移到您的程式碼中的 studentQuery3 上,以驗證指派的類型是否為 IEnumerable(Of String)

  3. 按 CTRL+F5 建置並執行應用程式。 記下主控台視窗中的結果。

在 Select 子句中建立匿名類型

  1. 新增本節中的程序代碼,以查看如何在查詢中使用匿名類型。 當您想要從數據源傳回數個字段,而不是完整記錄(先前範例中的記錄)或單一欄位(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
    
  2. 按 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 提供者類型的檔和範例:

另請參閱