Lambda Expressions Extension Methods Series 9 – OfType()

Then Enumerable.cs provides extension method OfType(). It can be used to select elements in an IEnumerable based on the type.

Method: OfType()

Arguments: None (Has Generic Argument)

Operates On: IEnumerable

Example: We have a list of objects, containing integer, float, string and character items. The OfType() method can be used to get elements which are integer.

IList<object> list = new List<object>();

list.Add(1);

list.Add(1.1);

list.Add(2);

list.Add(2.2);

list.Add(“string”);

list.Add(‘c’);

In order to select the elements which are int – the following code can be used.

var result = list.OfType<int>();

Here the OfType() method takes an int generic argument.

Output

The output of the above code will be:

1

2

Code Explained

In the above code we are having the following elements as inputs:

Element

Type

1

Integer

1.1

Float

2

Integer

2.2

Float

“string”

String

‘c’

Character

Extension Method Snapshot

You can find the snapshot of OfType () method usage as provided by Visual Studio.

Leave a Reply

Your email address will not be published. Required fields are marked *