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.

1 comment:

jamiei said...

Good tip, I created an SO question on this exact subject not so long ago.

It's worth noting that Cast< T> will raise an exception where it cannot cast the types contained in the list. You can also use OfType< T> to return _only_ those elements which can be cast to the specified type, which avoids any exceptions but may mean that your list is missing items if a wrong type gets in there somehow.