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:
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.
Post a Comment