본문 바로가기
프로그래밍/C# LINQ

C# Linq - Enumerable.OfType()

by bantomak 2024. 2. 16.

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

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

 

형식 매개 변수

TResult

스퀀스의 요소를 필터링할 형식

 

매개변수

source IEnumerable

요소를 필터링할 IEnumerable

 

반환

IEnumerable<TResult>

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

 

IEnumerable 컬렉션에서 원하는 TResult 형식을 선별하고 싶을 때 사용한다.

 

예제 코드

System.Collections.ArrayList fruits = new System.Collections.ArrayList(4);
fruits.Add("Mango");
fruits.Add("Orange");
fruits.Add("Apple");
fruits.Add(3.0);
fruits.Add("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.ToLower().Contains("n"));

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

 

출처

 

Enumerable.All<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Method (System.Linq)

Determines whether all elements of a sequence satisfy a condition.

learn.microsoft.com

'프로그래밍 > C# LINQ' 카테고리의 다른 글

C# Linq - Enumerable.Take()  (0) 2024.02.26
C# Linq - Enumerable.Reverse()  (0) 2024.02.19
C# Linq - Enumerable.Where()  (0) 2024.02.15
C# Linq - Enumerable.All()  (0) 2024.02.15
C# Linq - Enumerable.Range()  (0) 2023.12.18

댓글