.NET Tips and Tricks

Blog archive

Using LINQ with Collections that Don't Support LINQ, Revisited

In an earlier tip, I discussed how the OfType operator lets you run LINQ queries against collections that don't otherwise support LINQ. One reader of that column pointed out that, under the hood, a function named Cast was doing all the work. Another reader pointed out that what's special about OfType and Cast is that, unlike the other LINQ keywords, they work with collections that aren't generic types. Instead, OfType and Cast allow you to specify the type of the objects in the collection.

As an example of how to use Cast and OfType, imagine an ArrayList holding nothing but Customer objects:

Dim customers As New ArrayList
customers.Add(New Customer)
customers.Add(New Customer)

Both Cast and OfType will let you issue LINQ queries against the collection:

Dim custs = From c In customers.Cast(Of Customer)()
            Where c.CreditLimit = 0
            Select c

Dim custs = From c In customers.OfType(Of Customer)()
            Where c.CreditLimit = 0
            Select c

But what if the ArrayList contains a variety of objects? This collection contains both DeadbeatCustomer and PremiumCustomers:

customers.Add(New DeadbeatCustomer)
customers.Add(New PremiumCustomer)

Either Cast or OfType will let you work with this collection of diverse objects, but in very different ways. OfType will extract the objects of a specific type, so this example will process only the DeadbeatCustomer objects in the collection:

Dim custs = From c In customers.OfType(Of DeadbeatCustomer)()
            Where c.CreditLimit = 0
            Select c

Cast, on the other hand, will let you work with all items in the collection, provided they share an interface (i.e., inherit from some common base object or implement a common interface). This example assumes that both DeadbeatCustomer and PremiumCustomer interfaces both implement an interface named IBuyer:

Dim custs = From c In customers.Cast(Of IBuyer)()
            Where c.CreditLimit = 0
            Select c

So thanks, guys: This was your column. I'll send you a bill for writing it up.

Posted by Peter Vogel on 02/04/2014


comments powered by Disqus

Featured

Subscribe on YouTube