Casting populated List<BaseClass> to List<ChildClass>

I have a List<BaseClass> with members in it. I would like to cast the list (and all its members specifically) to a type List<ChildClass>, where ChildClass inherits BaseClass. I know I can get the same result through a foreach:

List<ChildClass> ChildClassList = new List<ChildClass>();
foreach( var item in BaseClassList )
{
    ChildClassList.Add( item as ChildClass );
}

But is there a neater way of doing this? Note - this is done on the WP7 platform.

Answers


You can do this if you are really sure all items are castable:

ChildClassList = BaseClassList.Cast<ChildClass>().ToList();

Your current code adds null if a BaseClass item cannot be cast to ChildClass. If that was really your intention, this would be equivalent:

ChildClassList = BaseClassList.Select(x => x as ChildClass).ToList();

But i'd rather suggest this, which includes type checking and will skip items that don't match:

ChildClassList = BaseClassList.OfType<ChildClass>().ToList();

The following is almost equivalent to your current code (the only missing thing is it doesn't add nulls for failed casts):

var childList = baseList.OfType<ChildClass>().ToList();

This will ignore instances where the list contains another derived class other than ChildClass.

You can also use:

var childList = baseList.Cast<ChildClass>().ToList();

But this will throw an InvalidCastException on things it cannot cast.


Need Your Help

How do interrupts in multicore/multicpu machines work?

operating-system kernel multicore

I recently started diving into low level OS programming. I am (very slowly) currently working through two older books, XINU and Build Your Own 32 Bit OS, as well as some resources suggested by the ...