Reputation: 4109
I now do something inefficient like this:
' Returns a collection of selected choices in a multichoice field
Dim MyField As NS.ChoiceValues = CType(Me.Form.Fields("Field").Value, NS.ChoiceValues)
If MyField.Choices.Item("Value 1") IsNot Nothing Then
' Do stuff to database choice Value 1, which has id 100
End If
If MyField.Choices.Item("Value 1") Is Nothing Then
' Do other stuff to database choice Value 1, which has id 100
End If
If MyField.Choices.Item("Value 2") IsNot Nothing Then
' Do stuff to database choice Value 2, which has id 200
End If
If MyField.Choices.Item("Value 2") Is Nothing Then
' Do other stuff to database choice Value 2, which has id 200
End If
...
This is very inefficient and becomes unreadable when the number of choice values increase. So I am trying to update this:
Dim Field1Choices As New Dictionary(Of Integer, String) From {
{100, "Value 1"},
{200, "Value 2"},
{300, "Value 3"},
{400, "Value 4"}
...
}
For Each FieldChoice As String In Field1Choices
If MyField.Choices.Item(var_a) ' var_a should be "Value 1", "Value 2", etc.
DoStuff.WithCoice(Me.Database, "SomeTable", var_b) 'var_b should be 100, 200 etc.
End If
Next
Obviously, this does not work. Because My array contains both integers and strings, For Each FieldChoice As String In Field1Choices
does not work.
How can I loop through the Field1Choices array so that var_a
and var_b
get get the values of the array values?
Upvotes: 1
Views: 11936
Reputation: 216353
Each entry in a Dictionary is returned as KeyValuePair type that has the property Value and the property Key.
In a For Each loop you don't need to declare the type of the iterator. It is identified correctly by the compiler looking at the type enumerated. In this case your Dictionary has an Integer key and a string value. So your KeyValuePair
iterator contains a Key of type Integer and a Value of type string for every entry in the dictionary
Dim Field1Choices As New Dictionary(Of Integer, String) From {
{100, "Value 1"},
{200, "Value 2"},
{300, "Value 3"},
{400, "Value 4"}
}
For Each FieldChoice In Field1Choices
Dim var_A = FieldChoice.Value
Console.WriteLine(var_A)
DIm var_B = FieldChoice.Key
Console.WriteLine(var_B)
'DoStuff.WithCoice(Me.Database, "SomeTable", var_B) 'var_b should be 100, 200 etc.
Next
Upvotes: 2