LINQ OfType() Method

  Total Views : 245
  Comments : 0
 
  Keywords : How to use linq oftype method to get only specified type of elements from collection in c# / vb.net with example, Linq oftype to select certain type of items from list with example

Here we will learn LINQ OfType method with example in c#, vb.net and how to use LINQ OfType method to get only specified type of elements from the list with example in c#, vb.net

LINQ OfType Conversion Operator

In LINQ OfType operator is used to return only the elements of specified type and other elements will be simply ignored from the list / collection.

Syntax of LINQ OfType Operator

Following is the syntax of using LINQ OfType operator to get specified type of elements from list / collection.

 

C# Code

 

IEnumerable<string> result = obj.OfType<string>();

VB.NET Code

 

Dim result As IEnumerable(Of String) = obj.OfType(Of String)()

If you observe above syntax we are trying to get only string elements from the “obj” collection by using OfType operator.

LINQ OfType Operator Example

Following is the example of LINQ OfType operator to get only 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 above example from “result” list we are trying to get only those elements which are of type string. The last element will be ignored because it is an integer.

Output LINQ OfType() Operator Example

Following is the result of LINQ OfType() operator example.

 

India

USA

UK

Australia

This is how we can use LINQ OfType() operator in c#, vb.net to get specified type of elements from list / collection.

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User