In LINQ, the OfType operator is used to return only the elements of a specified type, and other elements will be ignored from the list/collection.
Syntax of LINQ OfType Operator
Following is the syntax of using the LINQ OfType operator to get a specified type of elements from the list/collection.
LINQ OfType Syntax in C#
IEnumerable<string> result = obj.OfType<string>();
LINQ OfType Syntax in VB.NET
Dim result As IEnumerable(Of String) = obj.OfType(Of String)()
If you observe the above syntax, we are trying to get only string elements from the “obj” collection using the OfType operator.
LINQ OfType Operator Example
Following is the example of the LINQ OfType operator to get only the specified type of elements from the list/collection.
C# Code
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Linqtutorials
{
class Program
{
static void Main(string[] args)
{
ArrayList obj = new ArrayList();
obj.Add("India");
obj.Add("USA");
obj.Add("UK");
obj.Add("Australia");
obj.Add(1);
IEnumerable<string> result = obj.OfType<string>();
foreach (var item in result)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}
VB.NET Code
Module Module1
Sub Main()
Dim obj As New ArrayList()
obj.Add("India")
obj.Add("USA")
obj.Add("UK")
obj.Add("Australia")
obj.Add(1)
Dim result As IEnumerable(Of String) = obj.OfType(Of String)()
For Each item In result
Console.WriteLine(item)
Next
Console.ReadLine()
End Sub
End Module
If you observe the above example, from the “result” list, we are trying to get only the string type elements. The last element will be ignored because it is an integer.
Result of LINQ OfType() Operator Example
Following is the result of the LINQ OfType() operator example.
India
USA
UK
Australia
This is how we can use LINQ OfType() operator in c#, vb.net to get the specified type of elements from the list/collection.