6.15. Cast a Collection to a Specific Type

Problem

You need to convert a nongeneric collection, such as an ArrayList, into a generic collection so it will be capable of fully supporting LINQ.

Solution

Use the Cast or OfType extension method to cast the target collection to the specified type.

How It Works

As noted in several other recipes in this chapter, the System.Linq.Enumerable class contains all the extension methods that make up LINQ to Objects. Although the vast majority of these methods extend IEnumerable(Of T), a few of them actually extend IEnumerable. Two of the most important methods that are designed this way are Cast and OfType. Since these methods extend IEnumerable, it provides a mechanism to easily convert a collection (such ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.