Re: Casting/converting generic list types

Jon Skeet <[email protected]>
Newsgroups gmane.comp.windows.devel.dotnet.cx
Message-ID <[email protected]>
Mont Rothstein wrote:
> If I have List<A> where all of the elements are of type B.  How do I get
> List<B> from List<A>?  Do I have to iterate over List<A> and add each
> element to List<B>?

Yes, I'm afraid so.

> I've tried using "as List<B>" and "(List<B>)" both to no avail.
> List<T>.AddRange() must be of the same type T.
>
> ConvertAll() is an O(n) operation, and does a conversion which I don't
> really need.

Do you definitely have a performance issue in that area of the code? How
big are the lists?

> I have this situation occur fairly frequently because A is an  abstract
> superclass of a number of different classes and it has a method to return a
> List of objects of a subclass, but that list is always homogeneous.

Can you not just use a List<A> everywhere instead?

Jon

===================================
This list is hosted by DevelopMentor®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.