共用方式為


如何:使用 LINQ 查詢 ArrayList (Visual Basic)

使用 LINQ 查詢這類IEnumerable非泛型ArrayList集合時,您必須明確宣告範圍變數的類型,以反映集合中物件的特定類型。 例如,如果您有一個包含ArrayList物件的Student,您的From 子句看起來應該像這樣:

Dim query = From student As Student In arrList
'...

藉由指定範圍變數的類型,您將 ArrayList 中的每個項目轉換為 Student

在查詢表達式中使用明確型別的範圍變數相當於呼叫 Cast 方法。 Cast 如果無法執行指定的轉換,則會擲回例外狀況。 CastOfType 是兩種在非泛型 IEnumerable 型別上運作的標準查詢運算符方法。 在 Visual Basic 中,您必須明確呼叫 Cast 數據源上的 方法,以確保特定的範圍變數類型。 如需詳細資訊,請參閱查詢作業中的類型關聯性(Visual Basic)。

範例

下列範例示範透過 ArrayList的簡單查詢。 請注意,此範例會在程式代碼呼叫 Add 方法時使用物件初始化表達式,但這並非必要專案。

Imports System.Collections
Imports System.Linq

Module Module1

    Public Class Student
        Public Property FirstName As String
        Public Property LastName As String
        Public Property Scores As Integer()
    End Class

    Sub Main()

        Dim student1 As New Student With {.FirstName = "Svetlana",
                                     .LastName = "Omelchenko",
                                     .Scores = New Integer() {98, 92, 81, 60}}
        Dim student2 As New Student With {.FirstName = "Claire",
                                    .LastName = "O'Donnell",
                                    .Scores = New Integer() {75, 84, 91, 39}}
        Dim student3 As New Student With {.FirstName = "Cesar",
                                    .LastName = "Garcia",
                                    .Scores = New Integer() {97, 89, 85, 82}}
        Dim student4 As New Student With {.FirstName = "Sven",
                                    .LastName = "Mortensen",
                                    .Scores = New Integer() {88, 94, 65, 91}}

        Dim arrList As New ArrayList()
        arrList.Add(student1)
        arrList.Add(student2)
        arrList.Add(student3)
        arrList.Add(student4)

        ' Use an explicit type for non-generic collections
        Dim query = From student As Student In arrList
                    Where student.Scores(0) > 95
                    Select student

        For Each student As Student In query
            Console.WriteLine(student.LastName & ": " & student.Scores(0))
        Next
        ' Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()
    End Sub

End Module
' Output:
'   Omelchenko: 98
'   Garcia: 97

另請參閱