VB.NET ArrayList to List(Of T) typed copy/conversion - vb.net

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

Dim StronglyTypedList = OriginalArrayList.Cast(Of MyType)().ToList()
' requires `Imports System.Linq`

Duplicate.
Have a look at this SO-Thread: In .Net, how do you convert an ArrayList to a strongly typed generic list without using a 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)

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.

I would like to point out something about both the DirectCast and System.Linq.Cast (which are the same thing in the latest .NET at least.) These may not work if the object type in the array is defined by the user class, and is not easily convertable into object types that .NET recognizes. I do not know why this is the case, but it seems to be the problem in the software for which I am developing, and so for these we have been forced to use the inelegant loop solution.

Related

Defining the type of a List in vb.net at runtime

I'm creating a class at run time using typebuilder and after I create this class I want to define its type for a list like
dim fooList as new List(of DynamicClassName)
Since this doesn't exist at compile time of course it throws an error. When I generate this type I return the type so I can't do something like
dim newType = createNewType(foobar)
dim fooList as new List(of getType(newType))
How do I assign the type of a List at runtime?
You can create a List(Of T), but AFAIK you won't be able to cast it to a typed object. I've used the String type in the following example.
Dim list As Object = Activator.CreateInstance(GetType(List(Of )).MakeGenericType(New Type() {GetType(String)}))
Debug.WriteLine((TypeOf list Is List(Of String)).ToString())
Output
True
So in your case it would look like this:
Dim newType = createNewType(foobar)
'Creates a List(Of foobar):
Dim list As IList = Ctype(Activator.CreateInstance(GetType(List(Of )).MakeGenericType(New Type() {newType})), IList)
'Creates a BindingList(Of foobar):
Dim bindingList As IBindingList = Ctype(Activator.CreateInstance(GetType(BindingList(Of )).MakeGenericType(New Type() {newType})), IBindingList)
This does not answer your question, but may solve your problem.
Another option would be to use an ArrayList (for which you don't have to assign a type). You can see the details here: http://msdn.microsoft.com/en-us/library/system.collections.arraylist(v=vs.110).aspx.
Here is a basic example:
Dim anyArrayList as new ArrayList()
anyArrayList.add("Hello")
anyArrayList.add("Testing")

Casting Error when sorting with IComparer

I have an ArrayList of strings of the form "Q19_1_1", "Q19_10_1", "Q19_5_1".
With the normal sort method the list will be sorted as
"Q19_1_1"
"Q19_10_1"
"Q19_5_1"
But I would like to sort it numerically based off the second integer in name and then the third. So I would like:
"Q19_1_1"
"Q19_5_1"
"Q19_10_1"
My Sub:
Dim varSet As New ArrayList
varSet.Add("Q19_1_1")
varSet.Add("Q19_10_1")
varSet.Add("Q19_5_1")
varSet.Sort(New VariableComparer())
I have a IComparer:
Public Class VariableComparer
Implements IComparer(Of String)
Public Function Compare(ByVal x As String, ByVal y As String) As Integer Implements System.Collections.Generic.IComparer(Of String).Compare
Dim varPartsX As Array
Dim varPartsY As Array
varPartsX = x.Split("_")
varPartsY = y.Split("_")
Return String.Compare(varPartsX(1), varPartsY(1))
End Function
End Class
But when I attempt to sort I get the error:
Unable to cast object of type 'VBX.VariableComparer' to type 'System.Collections.IComparer'.
VariableComparer implements IComparer but I'm guessing it can't be of type IComparer(Of String)?
How can I resolve this issue? What am I missing?
Using a List(Of String) also gives you access to the LINQ extensions. Specifically the OrderBy and the ThenBy extensions. You could do it something like this:
Dim test3 As New List(Of String)({"Q19_1_1", "Q19_10_1", "Q19_5_1", "Q19_5_2"})
test3 = test3.OrderBy(Of Integer)(Function(s) Integer.Parse(s.ToString.Split("_"c)(1))) _
.ThenBy(Of Integer)(Function(s2) Integer.Parse(s2.ToString.Split("_"c)(2))).ToList
Casting to Integer gives you the proper sorting without using a new IComparer interface
You are correct - the issue is that you implemented IComparer(Of String), but not IComparer, which is a completely different interface.
If you switch to use a List(Of String) instead of ArrayList, it will work correctly.
This will also give you type safety within your collection.
In general, ArrayList (and the other System.Collections types) should be avoided in new development.

How to fill object variables defined in the dictionary based on JSON?

OK, that question sounds maybe a little confusing so I'll try to explain it with an example.
Pretend you have an object like this:
Class Something
Private varX As New Integer
Private varY As New String
'[..with the associated property definitions..]
Public Sub New()
End Sub
End Class
And another with:
Class JsonObject
Inherits Dictionary(Of String, String)
Public Function MakeObject() As Object 'or maybe even somethingObject
Dim somethingObject As New Something()
For Each kvp As KeyValuePair(Of String, String) In Me
'Here should happen something to use the Key as varX or varY and the Value as value for the varX or varY
somethingObject.CallByName(Me, kvp.Key, vbGet) = kpv.Value
Next
return somethingObject
End Function
End Class
I've got the 'CallByMe()' function from a previous question of myself
CallByName works different from the way you are trying to use it. Look at the documentation, it will tell you that in this particular case the correct usage would be
CallByName(Me, kvp.Key, vbSet, kpv.Value)
However, the function CallByName is part of a VB library that isn’t supported on all devices (notably it isn’t included in the .NET Mobile framework) and consequently it’s better not to use it.
Using proper reflection is slightly more complicated but guaranteed to work on all platforms.
Dim t = GetType(Something)
Dim field = t.GetField(kvp.Key, BindingFlags.NonPublic Or BindingFlags.Instance)
field.SetValue(Me, kvp.Value)

How to get the Key and Value from a Collection VB.Net

How do you get the key value from a vb.net collection when iterating through it?
Dim sta As New Collection
sta.Add("New York", "NY")
sta.Add("Michigan", "MI")
sta.Add("New Jersey", "NJ")
sta.Add("Massachusetts", "MA")
For i As Integer = 1 To sta.Count
Debug.Print(sta(i)) 'Get value
Debug.Print(sta(i).key) 'Get key ?
Next
Pretty sure you can't from a straight Microsoft.VisualBasic.Collection.
For your example code above, consider using a System.Collections.Specialized.StringDictionary. If you do, be aware that the Add method has the parameters reversed from the VB collection - key first, then value.
Dim sta As New System.Collections.Specialized.StringDictionary
sta.Add("NY", "New York")
'...
For Each itemKey in sta.Keys
Debug.Print(sta.Item(itemKey)) 'value
Debug.Print(itemKey) 'key
Next
I don't recommend using the Collection class, as that is in the VB compatibility library to make migrating VB6 programs easier. Replace it with one of the many classes in the System.Collections or System.Collections.Generic namespace.
It is possible to get a key with using Reflection.
Private Function GetKey(Col As Collection, Index As Integer)
Dim flg As BindingFlags = BindingFlags.Instance Or BindingFlags.NonPublic
Dim InternalList As Object = Col.GetType.GetMethod("InternalItemsList", flg).Invoke(Col, Nothing)
Dim Item As Object = InternalList.GetType.GetProperty("Item", flg).GetValue(InternalList, {Index - 1})
Dim Key As String = Item.GetType.GetField("m_Key", flg).GetValue(Item)
Return Key
End Function
Not using VB.Collection is recommended but sometimes we are dealing with code when it was used in past. Be aware that using undocumented private methods is not safe but where is no other solution it is justifiable.
More deailed information can be found in SO: How to use reflection to get keys from Microsoft.VisualBasic.Collection
Yes, it may well, but I want recomend that you use another Collection.
How to do you do with Reflection, the type Microsoft.VisualBasic.Collection contains some private fields, the field one should use in this case is "m_KeyedNodesHash" the field, and the field type is System.Collections.Generic.Dictionary(Of String, Microsoft.VisualBasic.Collection.Node), and it contains a property called "Keys", where the return type is System.Collections.Generic.Dictionary(Of String, Microsoft.VisualBasic.Collection.Node).KeyCollection, and the only way to get a certain key is to convert it to type IEnumerable(Of String), and the call ElementAt the function.
Private Function GetKey(ByVal col As Collection, ByVal index As Integer)
Dim listfield As FieldInfo = GetType(Collection).GetField("m_KeyedNodesHash", BindingFlags.NonPublic Or BindingFlags.Instance)
Dim list As Object = listfield.GetValue(col)
Dim keylist As IEnumerable(Of String) = list.Keys
Dim key As String = keylist.ElementAt(index)
Return key
End Function

Can I use generics to populate List(of t) with custom classes?

I have several different lists I want to call. They all have the same format for the class:
id, value, description, order. Instead of creating a bunch a classes to return the all of the many lists, I wanted to use generics and just TELL it what kind of list to return. However, I can not figure out how to populate the classes.
Here are 2 examples of function in my calling code. This should indicate the type of list and the stored proc used to get the data:
Public Function getTheEyeColors()
Dim glEyeColors As New GenericList
Return glEyeColors.GetALList(Of EyeColor)("GetAllEyeColors")
End Function
Public Function getTheHairColors()
Dim glHairColors As New GenericList
glHairColors.GetALList(Of HairColor)("GetAllHairColors")
End Function
And here is the code I am trying to use to build the generic list...
Public Function GetALList(Of t)(ByVal storedproc As String) As List(Of t)
Dim lstGenericList As New List(Of t)
Dim oGenericListItem As t
Dim oProviderFactory As New ProviderFactory
Dim oConnection As DbConnection
Dim oReader As System.Data.IDataReader
Dim oFactory As DbProviderFactory
Dim oFileMgt As New FileMgt
Dim oCmd As DbCommand
oFactory = oProviderFactory.GetFactory
oConnection = oProviderFactory.GetProviderConnection(oFactory)
oCmd = oConnection.CreateCommand
oCmd.CommandType = CommandType.StoredProcedure
oCmd.CommandText = storedproc
Using (oConnection)
oConnection.Open()
oReader = oCmd.ExecuteReader()
While oReader.Read
HERE IS WHERE I AM NOT SURE HOW TO POPULATE THE EYECOLOR OR HAIRCOLOR CLASS
lstGenericList.Add(oGenericListItem)
End While
oConnection.Close()
End Using
Return lstGenericList
End Function
You could add two generic constraints; I don't know how to express them in VB, but here's the C# version:
T : new() - there has to be a parameterless constructor
T : ICommonInterface - T has to implement an interface
You then put the common properties (ID, Value, Description, Order) into the interface, and you'll be able to create a new T(), set the properties and add it to the list.
EDIT:
The VB Syntax to specify that it must both be creatable and implement an interface is:
(Of T As {ICommonInterface, New})
The way Jon recommends to do it is probably a better way to go, but another way I've seen this done is the FillObject method in the DotNetNuke architecture. Basically it's a conventions based method that uses reflection to match the properties on an object to the values of a dataset.
I personally don't like this method, but it does mean you don't have to create a new implementation of the code to hydrate the object for each stored procedure.
The code is available in the full source download in the DNN project.
While oReader.Read
HERE IS WHERE I AM NOT SURE HOW TO POPULATE THE EYECOLOR OR HAIRCOLOR CLASS
Check out LinqToSql (System.Data.Linq) . You might be re-inventing it.