Enumerable.OfType<TResult> Method

public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source)

Description

Filters a sequence based on a specified type.

The OfType<TResult> method filters the elements of an IEnumerable based on a specified type. It returns only those elements that can be cast to the specified type.

Parameters

source

An IEnumerable<Object> whose elements to filter.

TResult

The type to filter the elements of the sequence by.

Returns

IEnumerable<TResult>

An IEnumerable<TResult> that contains only elements of the specified type from the input sequence.

Remarks

This method supports deferred execution. The values of source are not observed until the iterator is enumerated. For example, calling Count() or ToList() by using OfType<TResult> will cause iteration over source.

The type check is performed using runtime type checking. Elements that do not match the specified type are excluded.

Example

The following code example demonstrates how to use the OfType<TResult> method to filter a list of mixed types.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        ArrayList mixedList = new ArrayList() { 1, "hello", 3.14, "world", 5, true, "LINQ" };

        // Filter for strings
        IEnumerable<string> strings = mixedList.OfType<string>();

        Console.WriteLine("Strings in the list:");
        foreach (string str in strings)
        {
            Console.WriteLine(str);
        }

        // Filter for integers
        IEnumerable<int> numbers = mixedList.OfType<int>();

        Console.WriteLine("\nIntegers in the list:");
        foreach (int num in numbers)
        {
            Console.WriteLine(num);
        }
    }
}

Output:

Strings in the list:
hello
world
LINQ

Integers in the list:
1
5