.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Lambda Expressions Extension Methods Series 13 -OfType()

Posted By:Jean Paul       Posted Date: June 02, 2011    Points: 200    Category: LINQ    URL: http://www.dotnetspark.com  

Lambda Expressions Extension Methods Series 13 -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.


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend