Reputation: 8410
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
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
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
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
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