如何将基类型列表转换为派生类型的列表

时间:2013-03-07 14:45:50

标签: c# .net linq

从派生类到基类似乎有许多问题,但我的问题是如何将基类型列表转换为派生类型列表?

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
}

解决方案我最终得到的不是很优雅。

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});
    });
}

必须有更好的方法......

4 个答案:

答案 0 :(得分:6)

您可以使用Linq方法OfType<MyDerived>(),例如:

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

它将删除所有不是MyDerived类的项目

答案 1 :(得分:3)

基础列表转换为派生列表基本上是非类型安全的。

您的代码基础列表复制到派生列表。

你可以更简单地做到这一点:

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

答案 2 :(得分:3)

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();

答案 3 :(得分:1)

试试这个:

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();
}