Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Lambda Expressions Extension Methods Series 9 – OfType()

Posted by JP on November 13, 2011


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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s