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...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With