rob
rob

Reputation: 8410

How to cast a list of a base type to list of the derived type

There seems to be a number of questions going the other way, from a derived class to a base class but my issue is how to cast a list of a base type to list of the derived type?

public class MyBase {
    public int A;
}

public class MyDerived : MyBase {
    public int B;
}

public void MyMethod() {
    List<MyBase> baseCollection = GetBaseCollection();
    List<MyDerived> derivedCollection = (List<MyDerived>)baseCollection; // Which doesn't work
}

Solution I ended up with which is not very elegant.

public class MyBase {
    public int A;
}

public class MyDerived {
    public int B;
    public MyBase BASE;
}
public void MyMethod() {
    List<MyBase> baseCollection = GetBaseCollection();
    List<MyDerived> derivedCollection = new List<MyDerived>();
    baseCollection.ForEach(x=>{
        derivedCollection.Add(new derivedCollection(){ BASE = x});
    });
}

There must be a better way...

Upvotes: 3

Views: 1243

Answers (4)

Marek Musielak
Marek Musielak

Reputation: 27132

You can use Linq method OfType<MyDerived>(), e.g.:

List<MyDerived> derivedCollection = baseCollection.OfType<MyDerived>().ToList();

It will remove all the items which are not MyDerived class though

Upvotes: 6

Killo
Killo

Reputation: 300

Try this:

public class MyBase
{
    public int A;
}

public class MyDerived : MyBase
{
    public int B;

    public MyDerived(MyBase obj)
    {
        A = obj.A;
    }
}


public void MyMethod() {
    List<MyBase> baseCollection = GetBaseCollection();
    List<MyDerived> derivedCollection = baseCollection.Select(x => new MyDerived(x)).ToList();
}

Upvotes: 1

sll
sll

Reputation: 62504

using System.Linq;

// with exception in case of cast error
var derivedCollection = baseCollection.Cast<MyDerived>().ToList();

// without exception in case of cast error
var derivedCollection = baseCollection.OfType<MyDerived>().ToList();

Upvotes: 3

SLaks
SLaks

Reputation: 887453

Casting a list of base to a list of derived is fundamentally non-type-safe.

Your code copies a list of base to a list of derived.

You can do that more simply:

List<MyDerived> derivedCollection = baseCollection.ConvertAll(x => new derivedCollection(){ BASE = x});

Upvotes: 3

Related Questions