C# Enumerable OfType

Description

Filters the elements of an IEnumerable based on a specified type.

Syntax


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

Parameters

  • TResult - The type to filter the elements of the sequence on.
  • source - The IEnumerable whose elements to filter.

Example

The following code example demonstrates how to use OfType to filter the elements of an IEnumerable.


//from www .ja v  a2s. co m
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass{
  public static void Main(String[] argv){  

    System.Collections.ArrayList fruits = new System.Collections.ArrayList(4);
    fruits.Add("Java");
    fruits.Add("Orange");
    fruits.Add("Apple");
    fruits.Add(3.0);
    fruits.Add("Banana");

    IEnumerable<string> query1 = fruits.OfType<string>();

    foreach (string fruit in query1)
    {
        Console.WriteLine(fruit);
    }
    IEnumerable<string> query2 = fruits.OfType<string>().Where(fruit => fruit.ToLower().Contains("n"));

    foreach (string fruit in query2)
    {
        Console.WriteLine(fruit);
    }

  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Linq »




Enumerable