비제네릭 IEnumerable 컬렉션에서 LINQ를 사용해 ArrayList를 쿼리할 때, 컬렉션의 객체 유형을 반영하도록 범위 변수의 유형을 명시적으로 선언해야 합니다. 예를 들어 ArrayList에 Student
개체가 있는 경우 From 절은 다음과 같은 형태가 됩니다.
Dim query = From student As Student In arrList
'...
범위 변수의 형식을 지정하여 각 항목을 ArrayListStudent
에 캐스팅합니다.
쿼리 식에서 명시적으로 형식화된 범위 변수를 사용하는 것은 메서드를 호출 Cast 하는 것과 같습니다. Cast 는 지정된 캐스트를 수행할 수 없는 경우 예외가 발생합니다. Cast와 OfType는 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
참고하십시오
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET