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

Top 5 Contributors of the Month
Gaurav Pal

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

 Subscribe to Articles

Lambda Expressions Extension Method 10 - Cast()

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

Lambda Expressions Extension Method 10 - Cast()

Lambda Expressions Extension Method 10 - Cast()

The Cast() method is an interesting method over the Lambda Extension method series.

This method would not take any arguments except the Generic argument.  On calling the method it operates on the IEnumerable and casts the items into the specified Generic type.

This method is useful in converting a non-generic type like ArrayList to an IEnumerable.


Consider the following classes where Employee is the base class and Manager class deriving from it.

In the example, we are creating instance of 3 manager objects and storing in an ArrayList.

            ArrayList list = new ArrayList();

            list.Add(new Manager() { Id = 1, Salary = 1000 });

            list.Add(new Manager() { Id = 2, Salary = 2000 });

            list.Add(new Manager() { Id = 3, Salary = 3000 });


            IEnumerable<Employee> result = list.Cast<Employee>();


            foreach (Employee employee in result)




We should not confused the Cast() method with Select() method.

 The Select() method is  used to convert one type to another with the transformation statement as argument.  But Cast() is meant to cast a type to IEnumerable

Extension Method Snapshot

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

 Subscribe to Articles


Further Readings:


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