2
public class A {}

public class B : A {}

now what the best way to get this working

List<A> a;
List<B> b = new List<B>();
a = b; // throw Cannot convert List<B> to List<A>

Thank you

Proviste
  • 177
  • 13

1 Answers1

5

The List<T> type doesn't support covariance, so you can't assign a List<B> directly to a List<A> even though B itself is directly assignable to A. You'll need to do a pass through list b, converting and adding the items into list a as you go. The ConvertAll method is a convenient way to do this:

List<B> b = new List<B>();
// ...
List<A> a = b.ConvertAll(x => (A)x);
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • What the behavior difference between ConvertAll(x => (A)x) and Select(x => (A)x) ? – Proviste Mar 07 '11 at 10:08
  • 1
    `ConvertAll` is an instance method on the `List` class and creates a new `List` from the existing list. `Select` is an extension method that acts on any `IEnumerable` and creates a new `IEnumerable` sequence. Using `ConvertAll` should be *slightly* faster than `Select` since it can make some optimisations (for example, it can allocate the target array to the correct length at the outset rather than needing to resize on-the-fly, and it can access the source list's underlying array directly rather than needing to instantiate and use a separate enumerator object). – LukeH Mar 07 '11 at 10:18