LINQ를 사용하여 ArrayList를 쿼리하는 방법(C#)
LINQ를 사용하여 ArrayList 등의 제네릭이 아닌 IEnumerable 컬렉션을 쿼리하는 경우 컬렉션에 있는 개체의 특정 형식을 반영하도록 범위 변수의 형식을 명시적으로 선언해야 합니다. 예를 들어 Student
개체의 ArrayList가 있는 경우 from 절은 다음과 같아야 합니다.
var query = from Student s in arrList
//...
범위 변수의 형식을 지정하여 ArrayList의 각 항목을 Student
로 캐스팅합니다.
명시적 형식 범위 변수를 쿼리 식에 사용하는 것은 Cast 메서드 호출과 같습니다. 지정된 캐스트를 수행할 수 없는 경우 Cast에서 예외를 throw합니다. Cast 및 OfType은 제네릭이 아닌 IEnumerable 형식에서 작동하는 두 가지 표준 쿼리 연산자 메서드입니다. 자세한 내용은 LINQ 쿼리 작업의 형식 관계를 참조하세요.
예시
다음 예제에서는 ArrayList에 대한 단순 쿼리를 보여 줍니다. 이 예제에서는 코드가 Add 메서드를 호출할 때 개체 이니셜라이저를 사용하지만 요구 사항은 아닙니다.
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]);
}
}
}
/* Output:
Omelchenko: 98
Garcia: 97
*/
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기