Re: Casting/converting generic list types
Mont Rothstein <[email protected]>
| Newsgroups | gmane.comp.windows.devel.dotnet.cx |
|---|---|
| Message-ID | <[email protected]> |
I may or may not have a performance issue, it is a potential problem. I was primarily looking for a more elegant solution because looping over List<A> to create List<B> is just ugly. Even better than a standard way to convert/cast would be the ability to return a List<T> where T is either A or any subclass of A. I'm not really sure why they didn't allow for this, perhaps it will get added in the future. Thank you both for your suggestions and for confirming what I feared. -Mont On 9/27/06, Eames, Andrew <[email protected]> wrote: > > You could make a little generic wrapper class that implements IList<B> > and contains a List<A> > > And use it like > IList<B> iKnowTheyAreBs = new > ListWrapper<B>(somethingThatReturnsListOfA()) > Andrew > > -----Original Message----- > From: Discussion relating to the specifics of the C# and Managed C++ > languages [mailto:[email protected]] On Behalf Of Jon Skeet > Sent: Wednesday, September 27, 2006 3:22 PM > To: [email protected] > Subject: Re: [DOTNET-CX] Casting/converting generic list types > > 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(r) http://www.develop.com > > View archives and manage your subscription(s) at > http://discuss.develop.com > =================================== This list is hosted by DevelopMentor® http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com