views:

303

answers:

3

I have a 3rd party method that returns an old-style ArrayList, and I want to convert it into a typed ArrayList(Of MyType).

Dim udc As ArrayList = ThirdPartyClass.GetValues()
Dim udcT AS List(Of MyType) = ??

I have made a simple loop, but there must be a better way:

Dim udcT As New List(Of MyType)
While udc.GetEnumerator.MoveNext
    Dim e As MyType = DirectCast(udc.GetEnumerator.Current, MyType)
    udcT.Add(e)
End While
+1  A: 
Dim StronglyTypedList = OriginalArrayList.Cast(Of MyType)().ToList()
' requires `Imports System.Linq`
Mehrdad Afshari
Cast is not a member of ArrayList
vulkanino
@vulkanino: Yes, it's an *extension method*. As I said, it requires System.Linq namespace to be included in the current compilation unit.
Mehrdad Afshari
Sorry, I didn't see the "requires" part. Anyhow I don't want to include Linq only for that cast. :)
vulkanino
@vul Unless you're not referencing System.Core assembly in the first place, not "including" Linq is unlikely to be justifiable. It's just a name for a bunch of C# features. It's a simple C# method and it's not something that has a big overhead. You could also call the method directly with `System.Linq.Enumerable.ToList(System.Linq.Enumerable.Cast(Of MyType)(OriginalArrayList))`
Mehrdad Afshari
A: 

Duplicate. Have a look at this SO-Thread: http://stackoverflow.com/questions/786268/in-net-how-do-you-convert-an-arraylist-to-a-strongly-typed-generic-list-without

In VB.Net with Framework < 3.5:

Dim arrayOfMyType() As MyType = DirectCast(al.ToArray(GetType(MyType)), MyType())
Dim strongTypeList As New List(Of MyType)(arrayOfMyType)
Tim Schmelter
@Tim this solution is concise but creates a temporary "standard" array.
vulkanino
@Vulkanino: you could write it in one line but without extension methods you must create an array implicitely with toArray or fill the list in a loop. Hence its always expensive and may not be used repetitive.
Tim Schmelter
A: 

What about this?

Public Class Utility

    Public Shared Function ToTypedList(Of C As {ICollection(Of T), New}, T)(ByVal list As ArrayList) As C

        Dim typedList As New C
        For Each element As T In list
            typedList.Add(element)
        Next

        Return typedList
    End Function

End Class

If would work for any Collection object.

vulkanino