Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a List<BaseClass> to List<DerivedClass>

Tags:

c#

.net

Given the following class definitions:

public class BaseClass
{
    public string SomeProp1 { get; set; }
}

public class DerivedClass : BaseClass
{
    public string SomeProp2 { get; set; }
}

How can I take a List<BaseClass> and convert it to a List<DerivedClass>?

In my real-world scenario BaseClass has a whole bunch of properties that I don't want to have to copy over one-by-one (and then remember to maintain if an additional property gets added).

Adding a parameterised constructor to BaseClass is not an option as this class is defined by a WCF service reference.

like image 928
Richard Ev Avatar asked Feb 05 '09 15:02

Richard Ev


2 Answers

List<DerivedClass> result = 
    listBaseClass.ConvertAll(instance => (DerivedClass)instance);

Actually ConvertAll is good when you need to create new objects based on the original, when you just need to cast you can use the following

List<DerivedClass> result = 
    listBaseClass.Cast<DerivedClass>().ToList();

If not all of the items in your list can be cast to DerivedClass then use OfType instead

List<DerivedClass> result =
    listBaseClass.OfType<DerivedClass>().ToList();
like image 148
Peter Morris Avatar answered Nov 08 '22 11:11

Peter Morris


You can't convert the actual object, but it's easy to create a new list with the converted contents:

List<BaseClass> baseList = new List<BaseClass>(...);
// Fill it here...

List<DerivedClass> derivedList = baseList.ConvertAll(b => (DerivedClass) b);

Or if you're not using C# 3:

List<DerivedClass> derivedList = baseList.ConvertAll<DerivedClass>(delegate
    (BaseClass b) { return (DerivedClass) b; };

This assumes that the original list was actually full of instances of DerivedClass. If that's not the case, change the delegate to create an appropriate instance of DerivedClass based on the given BaseClass.

EDIT: I'm not sure why I didn't just post a LINQ solution:

List<DerivedClass> derivedList = baseList.Cast<DerivedClass>().ToList();
like image 17
Jon Skeet Avatar answered Nov 08 '22 12:11

Jon Skeet