Filtering Operator OfType

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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(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:



OfType in Method Syntax:

You can use OfType() 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.



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.