Convert from List<A> to List<B>

  • Thread starter Thread starter bob_jeffcoat
  • Start date Start date
B

bob_jeffcoat

Hi,

Have class B which subclasses from class A. I have a List<B> and I'm
trying to get a List<A> without writing a stupid loop everytime I want
to do it. So I tried this method:

public static List<Destination> ConvertList<Source,
Destination>(List<Source> sourceList) where Destination : Source
{
List<Destination> result = new List<Destination>();
foreach (Source aSource in sourceList)
{
result.Add(aSource as Destination);
}
return result;
}

It didn't work, is it possible?

Why isn't there a method like this:
List<B> aList = new List<B>();
List<A> newList = aList.Convert<A>();

Any ideas?

Thanks,
 
Like so?

List<B> aList = new List<B>();
List<A> newList = aList.ConvertAll<A>(delegate(B item) {return (A) (object)
item;});

The (object) cast is needed where an explicit cast operator is not provided
by the class - or you could build the replacement objects yourself.

Marc
 
Additional: I didn't spot the "B subclasses A"; this means you can drop the
(object) cast

Finally - is this so you can can pass a List<A> as method parameters? If so,
note that this is a covariance issue, and can be resolved through generics
(see Right() below)

Marc

static void Main() {
List<B> aList = new List<B>();
List<A> newList = aList.ConvertAll<A>(delegate(B item) { return
(A)item; });

Wrong(aList);
Right(aList);
}
public static void Wrong(List<A> items) {
//do stuff with each A
}
public static void Right<T>(List<T> items) where T : A{
//do stuff with each T, which can also be treated as A
}
public class A { }
public class B : A { }
 
Hi,

Have class B which subclasses from class A. I have a List<B> and I'm
trying to get a List<A> without writing a stupid loop everytime I want
to do it. So I tried this method:

public static List<Destination> ConvertList<Source,
Destination>(List<Source> sourceList) where Destination : Source
{
List<Destination> result = new List<Destination>();
foreach (Source aSource in sourceList)
{
result.Add(aSource as Destination);
}
return result;
}

It didn't work, is it possible?

If you reverse the where constraint, this works:

public static List<Destination> ConvertList<Source,
Destination>(List<Source> sourceList)
where Source : Destination
{
List<Destination> result = new List<Destination>();

foreach (Source aSource in sourceList)
result.Add(aSource);

return result;
}

///ark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top