LINQ (Language Integrated Query) is a powerful feature of the .NET framework that allows developers to query various data sources using a unified syntax. One of the useful operators in LINQ is the OfType operator, which enables filtering of elements based on their type. In this article, we will explore the LINQ OfType Operator.

What is OfType Operator in LINQ?

The OfType operator in LINQ is used to filter elements in a collection based on their type. It returns only the elements of the specified type and filters out any other elements. This operator is particularly useful when dealing with collections that contain multiple types.

For example, if we have a collection that stores both integer and string values, and if we need to fetch either only the integer values or only string values from that collection then we need to use the LINQ OfType Operator. Following is the signature of the LINQ OfType Method.

LINQ OfType Method in C#

Let’s say, we have a collection of type Objects. As we know the Object class is the superclass of all data types, so we can store any type of values in it like below. Now our requirement is to fetch all the integer values from the collection by ignoring the string values. We can achieve this very easily by using the LINQ OfType Method in C# as follows.

Output: 50 10 20 30 40

LINQ OfType Operator in C#

We can achieve this using two ways i.e. using OfType Method and IS Operator. In the following example, the collection contains both string and integer values and we are only fetching the string values using both OfType method and IS Operator with the Query syntax.

Output:

Let’s say, we want to retrieve all the names whose length is greater than 3 and all the integer number which is greater than 30. Here we will use the OfType Method to retrieve all the integers which are greater than 30 and the “is” operator to retrieve all the strings with lengths greater than 3 characters.

OfType Operator in C# with Where Condition

Now, let us see how we can use the OfType in C# with both Method and Query Syntax with the Where Condition. In the below example, we are retrieving all the numbers which are greater than 30 using both Method and Query Syntax using the OfType operator.

Note: In LINQ, the Where Extension Method is used to filter the data source based on a condition i.e. predicate function. The OfType Extension Method is used to filter the data source based on a given type. And we can use both Where and OfType Methods multiple times in a single LINQ Query.

Leave a Comment