VB.NET ArrayList for List (Of T) typed copy / conversion

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

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

I made a simple loop, but there should 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 
+6
type-conversion
source share
4 answers
 Dim StronglyTypedList = OriginalArrayList.Cast(Of MyType)().ToList() ' requires `Imports System.Linq` 
+17
source share

Duplicate Take a look at this SO-Thread: In .Net, how do you convert an ArrayList to a strongly typed shared list without using foreach?

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) 
0
source share

How 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 it worked for any Collection object.

0
source share

I would like to point something to both DirectCast and System.Linq.Cast (which are at least the same in the latest .NET.) They may not work if the type of the object in the array is defined by a user class and is not easy convert to object types that .NET recognizes. I don’t know why this is so, but it seems that the problem is in the software for which I am developing, and therefore we have to use the inelegant loop solution for this.

0
source share

All Articles