-1

I have 2 classes

public class A
{
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public string prop3 { get; set; }
}

public class B : A
{
    public string prop4 { get; set; }
}

And I have a method to fill a List with type B.

Question: What is the easiest way to get the result into List<A>

List<B> BList = new List<B>();
BList = GetData(); //fill List with Data
List<A> AList = (List<A>)BList; // convert? cast?

Class A has all fields of Class B so there must be a easy way to get from B to A.

c0rd
  • 1,329
  • 1
  • 13
  • 20

2 Answers2

2

You can use a Linq function:

List<A> AList = BList.Cast<A>().ToList();
Fratyx
  • 5,717
  • 1
  • 12
  • 22
1

You will have to create a new List<A> instance with references to all the items from BList:

List<A> AList = new List<A>(BList);

That's because List<T> is not covariant (and can't be).

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263