영어로 읽기

다음을 통해 공유


Enumerable.OfType<TResult>(IEnumerable) 메서드

정의

지정된 형식에 따라 IEnumerable의 요소를 필터링합니다.

public static System.Collections.Generic.IEnumerable<TResult> OfType<TResult> (this System.Collections.IEnumerable source);

형식 매개 변수

TResult

시퀀스의 요소를 필터링할 형식입니다.

매개 변수

source
IEnumerable

요소를 필터링할 IEnumerable입니다.

반환

IEnumerable<TResult>

TResult 형식의 입력 시퀀스에서 가져온 요소가 들어 있는 IEnumerable<T>입니다.

예외

source이(가) null인 경우

예제

다음 코드 예제에서는 를 사용하여 OfType 의 요소를 필터링하는 방법을 보여 줍니다 IEnumerable.

System.Collections.ArrayList fruits = new()
{
    "Mango",
    "Orange",
    null,
    "Apple",
    3.0,
    "Banana"
};

// Apply OfType() to the ArrayList.
IEnumerable<string> query1 = fruits.OfType<string>();

Console.WriteLine("Elements of type 'string' are:");
foreach (string fruit in query1)
{
    Console.WriteLine(fruit);
}

// The following query shows that the standard query operators such as
// Where() can be applied to the ArrayList type after calling OfType().
IEnumerable<string> query2 =
    fruits.OfType<string>().Where(fruit =>
    fruit.Contains('n', StringComparison.CurrentCultureIgnoreCase));

Console.WriteLine("\nThe following strings contain 'n':");
foreach (string fruit in query2)
{
    Console.WriteLine(fruit);
}

// This code produces the following output:
//
// Elements of type 'string' are:
// Mango
// Orange
// Apple
// Banana
//
// The following strings contain 'n':
// Mango
// Orange
// Banana

설명

이 메서드는 지연 된 실행을 사용 하 여 구현 됩니다. 즉시 반환 값은 작업을 수행 하는 데 필요한 모든 정보를 저장 하는 개체입니다. 이 메서드가 나타내는 쿼리는 개체를 직접 호출 GetEnumerator 하거나 C# 또는 For Each Visual Basic에서 를 사용하여 foreach 개체를 열거할 때까지 실행되지 않습니다.

메서드는 OfType<TResult>(IEnumerable) null이 아니고 형식TResult과 호환되는 의 source 요소만 반환합니다. 요소를 형식 TResult으로 캐스팅할 수 없는 경우 예외를 받으려면 를 사용합니다 Cast<TResult>(IEnumerable).

이 메서드는 와 같이 매개 변수가 없는 형식의 컬렉션에 적용할 수 있는 몇 안 되는 표준 쿼리 연산자 ArrayList메서드 중 하나입니다. 형식을 확장하기 IEnumerable때문 OfType 입니다. OfType 매개 변수가 IEnumerable<T> 있는 형식을 기반으로 하는 컬렉션에만 적용할 수 없지만 매개 변수 IEnumerable 가 없는 형식을 기반으로 하는 컬렉션도 적용할 수 있습니다.

를 구현IEnumerable하는 OfType 컬렉션에 적용하면 표준 쿼리 연산자를 사용하여 컬렉션을 쿼리할 수 있습니다. 예를 들어 의 형식 인수 Object 를 지정하면 표준 쿼리 연산자를 적용할 OfType 수 있는 형식의 IEnumerable<Object> 개체가 C# 또는 IEnumerable(Of Object) Visual Basic에서 반환됩니다.

적용 대상

제품 버전
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0