C# OfType() Method


Filter a collection on the basis of each of its elements type.

Let’s say you have the following list with integer and string elements −

list.Add("Katie");
list.Add(100);
list.Add(200);

To filter collection and get only elements with string type.

var myStr = from a in list.OfType<string>() select a;

Work the same for integer type.

var myInt = from a in list.OfType<int>() select a;

The following is the complete code −

Example

 Live Demo

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);
      }
   }
}

Output

Strings...
Katie
Brad
Integer...
100
200
300
400
600
700

Updated on: 23-Jun-2020

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements