繁体   English   中英

如何循环遍历 VB.Net 数组?

[英]How do I loop through a VB.Net array?

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

' 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. 所以我想更新这个:

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

显然,这行不通。 因为我的数组同时包含整数和字符串,所以For Each FieldChoice As String In Field1Choices不起作用。

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

Dictionary 中的每个条目都作为KeyValuePair类型返回,该类型具有属性Value和属性Key
在 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM