LINQ を使用して ArrayList などの非ジェネリック IEnumerable コレクションに対してクエリを実行する場合は、コレクション内のオブジェクトの特定の型を反映するように範囲変数の型を明示的に宣言する必要があります。 たとえば、Student
オブジェクトのArrayListがある場合、From 句は次のようになります。
Dim query = From student As Student In arrList
'...
範囲変数の型を指定することで、 ArrayList 内の各項目を Student
にキャストします。
クエリ式で明示的に型指定された範囲変数を使用することは、 Cast メソッドを呼び出すことと同じです。 Cast は、指定したキャストを実行できない場合に例外をスローします。 Cast OfTypeは、非ジェネリックIEnumerable型で動作する 2 つの標準クエリ演算子メソッドです。 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
こちらも参照ください
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET