Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

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...

like image 588
rob Avatar asked Dec 02 '25 05:12

rob


1 Answers

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

like image 145
Marek Musielak Avatar answered Dec 04 '25 20:12

Marek Musielak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!