Friday, November 06, 2009

Casting lists using LINQ #2

In my previous post I showed the LINQ way to cast List<SomeDeriveType> to List<SomeBaseObject>.

IEnumerable<BaseObject> baseObjects
= DerivedList.Cast<BaseObject>;
Great stuff!

As @jamiei commented this will raise an exception if the cast fails. OfType<T> will return only the elements of type T despite the fact that you have different derived types in one list. So suppose you have an Animal class and a Cat and Dog class that derive from Animal you could do something like this:
List<Animal> animalList = new List<Animal>();
new Dog("Dog1"));
new Dog("Dog2"));
new Dog("Dog3"));
new Cat("Cat1"));
new Cat("Cat2"));
new Cat("Cat3"));
//Get the dogs
IEnumerable<Dog> dogList = animalList.OfType<Dog>();
//Get the cats
IEnumerable<Cat> catList = animalList.OfType<Cat>();

LINQ makes it very easy to seperate the Dogs from the Cats!


Unknown said...

The first OffType should have one f less :-)

Good post!


william said...

Good post, this tip is handy!

Roland Beenhakker said...

@wiert Thanks, corrected the typo.

Use an image as your UIBarButtonItem

Using an image as your UIBarButtonItem in your navigationcontroller bar can only be achieved by using a common UIButton as the BarButtonItem...