Zeus
Zeus

Reputation: 1600

Generate a property name in a loop

I'm trying to find a way of loading a single record with 25 columns into a datatable.

I could list all 25 variables called SPOT1 to SPOT25 (columns in the datatable) but I'm looking for more concise method like using a loop or dictionary.

The code below shows two methods, a 'long' method which is cumbersome, and a 'concise' method which I'm trying to get help with.

Public dctMC As Dictionary(Of String, VariantType)
Dim newMC As New MONTE_CARLO()

'long method: this will work but is cumbersome
newMC.SPOT1=999
newMC.SPOT2=887
...
newMC.SPOT25=5

'concise method:  can it be done more concisely, like in a loop for example?
 Dim k As String

For x = 1 To 25
    k = "SPOT" & CStr(x)
    newMC.K = dctMC(k)    'convert newMC.k to newMC.SPOT1 etc
Next

'load record
DATA.MONTE_CARLOs.InsertOnSubmit(newMC)

Upvotes: 0

Views: 50

Answers (1)

SSS
SSS

Reputation: 5413

Per the others, I think there are better solutions, but it is possible...

Public Class MONTE_CARLO
  Private mintSpot(-1) As Integer
  Property Spot(index As Integer) As Integer
    Get
      If index > mintSpot.GetUpperBound(0) Then
        ReDim Preserve mintSpot(index)
      End If
      Return mintSpot(index)
    End Get
    Set(value As Integer)
      If index > mintSpot.GetUpperBound(0) Then
        ReDim Preserve mintSpot(index)
      End If
      mintSpot(index) = value
    End Set
  End Property
End Class

Usage...

Dim newMC As New MONTE_CARLO
For i As Integer = 0 To 100
  newMC.Spot(i) = i
Next i
MsgBox(newMC.Spot(20))

Upvotes: 1

Related Questions