如何循环VB.Net数组?

时间:2014-10-02 16:37:45

标签: arrays vb.net loops foreach

我现在做这样低效的事情:

' 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

...

这是非常低效的,并且当选择值的数量增加时变得不可读。所以我想更新一下:

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

显然,这不起作用。因为My数组包含整数和字符串,For Each FieldChoice As String In Field1Choices不起作用。

如何遍历Field1Choices数组,以便var_avar_b获取数组值的值?

1 个答案:

答案 0 :(得分:0)

词典中的每个条目都返回为KeyValuePair类型,其属性为,属性为
在For Each循环中,您不需要声明迭代器的类型。查看枚举类型的编译器可以正确识别它。在这种情况下,您的Dictionary具有Integer键和字符串值。所以你的KeyValuePair迭代器包含一个Integer类型的Key和一个字典中每个条目的string类型的值

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