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>();
animalList.Add(
new Dog("Dog1"));
animalList.Add(
new Dog("Dog2"));
animalList.Add(
new Dog("Dog3"));
animalList.Add(
new Cat("Cat1"));
animalList.Add(
new Cat("Cat2"));
animalList.Add(
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!

3 comments:

Unknown said...

The first OffType should have one f less :-)

Good post!

--jeroen

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...