Filtering Operator - OfType

The OfType operator filters the collection based on the ability to cast an element in a collection to a specified type.

OfType in Query Syntax:

Use OfType operator to filter the above collection based on each element's type

Example: OfType operator in C#

IList mixedList = new ArrayList();
mixedList.Add(0);
mixedList.Add("One");
mixedList.Add("Two");
mixedList.Add(3);
mixedList.Add(new Student() { StudentID = 1, StudentName = "Bill" });

var stringResult = from s in mixedList.OfType<string>()
                   select s;

var intResult = from s in mixedList.OfType<int>()
                select s;

Example: OfType operator in VB.Net:

Dim stringResult = From s In mixedList.OfType(Of String)()

The above sample queries will return items whose type is string in the mixedList. stringResult contains following elements after execution:

One
Two
0
3
Bill

OfType in Method Syntax:

You can use OfType<TResult>() extension method in linq method syntax as shown below.

Example: OfType in C#

var stringResult = mixedList.OfType<string>();

Example: OfType in VB.Net

Dim stringResult = mixedList.OfType(Of String)

stringResult would contain following elements.

One
Two

Points to Remember :

  1. The Where operator filters the collection based on a predicate function.
  2. The OfType operator filters the collection based on a given type
  3. Where and OfType extension methods can be called multiple times in a single LINQ query.

Visit MSDN for more information on Filtering operators.