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!

Wednesday, November 04, 2009

Casting lists using LINQ #1

I have been doing lately much work on a .NET 3.5 application using LINQ. LINQ is a great way to manipulate data. I still consider myself a 'LINQ rookie' so I discover everyday something new.

One thing that floated around my head a while was the problem that you can't cast a List<SomeDerivedObject> to List<SomeBaseObject>.
A poorman's solution to this was to loop the objects from the one list into the other list. Not an elegant solution though.....

I discovered that you can do this easily with LINQ. When you use a IEnumerable<T> you can do this like this:

IEnumerable<BaseObject> baseObjects
= DerivedList.Cast<BaseObject>;

Where DerivedList holds objects that inherit from BaseObject.
With a List<T> you could do something like this(copy):
List<BaseObject> baseObjects =
new List<BaseObject>(DerivedList.Cast<BaseObject>());

A great LINQ resource is 101 LINQ samples on MSDN.