Share via


방법: LINQ를 사용하여 ArrayList 쿼리

LINQ를 사용하여 ArrayList와 같은 제네릭이 아닌 IEnumerable 컬렉션을 쿼리할 때 컬렉션의 특정 개체 형식을 반영하도록 범위 변수의 형식을 명시적으로 선언해야 합니다. 예를 들어, Student 개체의 ArrayList가 있는 경우 from 절(C#) 또는 From 절(Visual Basic)은 다음과 같아야 합니다.

// C#
var query = from Student s in arrList
... 
'Visual Basic
Dim query = From student As Student In arrList 
...

범위 변수의 형식을 지정하면 ArrayList의 각 항목을 Student로 캐스팅합니다.

쿼리 식에서 명시적으로 형식화된 범위 변수를 사용하는 것은 Cast<TResult> 메서드를 호출하는 것과 같습니다. 지정한 캐스트를 수행할 수 없는 경우 Cast<TResult>은 예외를 throw합니다. Cast<TResult>OfType<TResult>은 제네릭이 아닌 IEnumerable 형식에서 연산을 수행하는 두 개의 표준 쿼리 연산자 메서드입니다. Visual Basic의 경우 범위 변수가 특정 형식을 갖도록 하려면 데이터 소스에 대해 Cast<TResult> 메서드를 명시적으로 호출해야 합니다. 자세한 내용은쿼리 작업의 형식 관계(Visual Basic)LINQ 쿼리 작업의 형식 관계(C#)를 참조하십시오.

예제

다음 예제에서는 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
using System;
using System.Collections;
using System.Linq;

namespace NonGenericLINQ
{
    public class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int[] Scores { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ArrayList arrList = new ArrayList();
            arrList.Add(
                new Student
                    {
                        FirstName = "Svetlana", LastName = "Omelchenko", Scores = new int[] { 98, 92, 81, 60 }
                    });
            arrList.Add(
                new Student
                    {
                        FirstName = "Claire", LastName = "O’Donnell", Scores = new int[] { 75, 84, 91, 39 }
                    });
            arrList.Add(
                new Student
                    {
                        FirstName = "Sven", LastName = "Mortensen", Scores = new int[] { 88, 94, 65, 91 }
                    });
            arrList.Add(
                new Student
                    {
                        FirstName = "Cesar", LastName = "Garcia", Scores = new int[] { 97, 89, 85, 82 }
                    });

            var query = from Student student in arrList
                        where student.Scores[0] > 95
                        select student;

            foreach (Student s in query)
                Console.WriteLine(s.LastName + ": " + s.Scores[0]);

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}
/* Output: 
    Omelchenko: 98
    Garcia: 97
*/

참고 항목

개념

LINQ to Objects