각 요소 유형을 기준으로 컬렉션을 필터링합니다.
정수 및 문자열 요소가 있는 다음 목록이 있다고 가정해 보겠습니다. -
list.Add("Katie");
list.Add(100);
list.Add(200); 컬렉션을 필터링하고 문자열 유형의 요소만 가져옵니다.
var myStr = from a in list.OfType<string>() select a;
정수 유형에 대해서도 동일하게 작동합니다.
var myInt = from a in list.OfType<int>() select a;
다음은 완전한 코드입니다 -
예시
using System;
using System.Linq;
using System.Collections;
public class Demo {
public static void Main() {
IList list = new ArrayList();
list.Add("Katie");
list.Add(100);
list.Add(200);
list.Add(300);
list.Add(400);
list.Add("Brad");
list.Add(600);
list.Add(700);
var myStr = from a in list.OfType<string>() select a;
var myInt = from a in list.OfType<int>() select a;
Console.WriteLine("Strings...");
foreach (var strVal in myStr) {
Console.WriteLine(strVal);
}
Console.WriteLine("Integer...");
foreach (var intVal in myInt) {
Console.WriteLine(intVal);
}
}
} 출력
Strings... Katie Brad Integer... 100 200 300 400 600 700