In this Video, I am going to discuss the OfType Operator in LINQ with examples. Please read our previous Video before proceeding to this Video where we discussed the where filtering operator in C# with some examples. The OfType Operator in C# belongs to the filtering category of LINQ operators. As part of this Video, we are going to discuss the following pointers in detail.
What is OfType Operator in LINQ ?. The Complete Microsoft .Net 6 LINQ Developer Course 2023 [Videos].
- What is OfType Operator in LINQ?
- Examples using both Method and Query syntax.
- Difference between OfType and is Operator in C#.NET.
What is OfType Operator in LINQ?
The OfType Operator in LINQ is used to filter specific type data from a data source based on the data type we passed to this operator. 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 the string values from that collection then we need to use the OfType operator.
Following is the signature of the OfType method. It is implemented as a generic type, so there are no overloaded versions available for this method. This method can take any type of data type and then fetch the specified data type values from the collection.
public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source);
Let say, we have a collection of type object. 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 OfType operator in C# like below.
The complete code is given below.
OfType Operator Using Method syntax in C#.NET:
OfType Operator Using Query Syntax in C#.NET:
There is no such OfType operator available in query syntax. Instead “is” operator is available which we can use to filter data based on a type from a data source. In the following example, the collection contains both string and integer values and we need to fetch only the string values.
OfType and is Operator with a condition in C#.NET:
Let 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 OfType operator to retrieve all the names and “is” operator to retrieve all the integers along with the required conditions.